﻿
Imports AutoMapper
Imports CookComputing.XmlRpc
Imports FTTK.Extensions
Imports FTTK.Services.EventArgs
Imports FTTK.Entities
Imports FTTK.Exceptions
Imports FTTK.Services.Interfaces
Imports System.Net
Imports FTTK.XmlRpc.Interfaces
Imports FTTK.XmlRpc

Namespace Services.Implementations.XmlRpc
    ''' <summary>
    ''' Provides services relating to a partner account
    ''' </summary>
    ''' <remarks></remarks>
    Public Class PartnerService
        Inherits BaseService
        Implements IPartnerService

        Shared Sub New()
            Try
                PartnerServiceMapping.DefineMapping()
            Catch ex As Exception

            End Try
        End Sub

        ''' <summary>
        ''' Initializes a new instance of the <see cref="PartnerService" /> class.
        ''' </summary>
        ''' <param name="cacheAdapter">The cache adapter.</param>
        ''' <remarks></remarks>
        Public Sub New(cacheAdapter As ICacheAdapter)
            MyBase.New(cacheAdapter)
            CreateProxies()
        End Sub

        ''' <summary>
        ''' Initializes a new instance of the <see cref="PartnerService" /> class.
        ''' </summary>
        ''' <param name="apiKey">The API key.</param>
        ''' <param name="cacheAdapter">The cache adapter.</param>
        ''' <remarks></remarks>
        Public Sub New(apiKey As String, cacheAdapter As ICacheAdapter)
            MyBase.New(apiKey, cacheAdapter)
            CreateProxies()
        End Sub

        ''' <summary>
        ''' Initializes a new instance of the <see cref="PartnerService" /> class.
        ''' </summary>
        ''' <remarks></remarks>
        Public Sub New()
            MyBase.New()
            CreateProxies()
        End Sub

        ''' <summary>
        ''' Initializes a new instance of the <see cref="PartnerService" /> class.
        ''' </summary>
        ''' <param name="apiKey">The API key.</param>
        ''' <remarks></remarks>
        Public Sub New(apiKey As String)
            MyBase.New(apiKey)
            CreateProxies()
        End Sub

        Private Sub CreateProxies()
            Me.MediaDataProxy = CreateProxy(Of IMediaData)()
            Me.UserProxy = CreateProxy(Of IUser)()
        End Sub

        Protected Property MediaDataProxy As IMediaData
        Protected Property UserProxy As IUser

#Region "GetRepresentativeCategories"

        ''' <summary>
        ''' This method returns childs of a parent category in fotolia representative category system. 
        ''' This method could be used to display a part of the category system or the all tree. 
        ''' Fotolia categories system counts three levels
        ''' </summary>
        ''' <param name="languageId">The language id.</param>
        ''' <param name="idCategoryParent">The id category parent.</param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Function GetRepresentativeCategories(ByVal languageId As Integer,
                                                    Optional ByVal idCategoryParent As Integer? = Nothing) As IEnumerable(Of Category) Implements IPartnerService.GetRepresentativeCategories
            Dim retVal As IEnumerable(Of Category) = Nothing
            Try
                Dim idParent As Integer = 0
                If idCategoryParent.HasValue Then
                    idParent = idCategoryParent.Value
                End If
                retVal = ExecuteQuery(Of IEnumerable(Of Category))("GetRepresentativeCategories",
                                                    Function() SearchProxy.GetCategories1(Me.Authentication, languageId, idParent),
                                                    Me.Authentication,
                                                    languageId,
                                                    idParent)
            Catch ex As Exception
                ManageException(ex)
            End Try
            Return retVal
        End Function

        Private Sub GetRepresentativeCategoriesCallBack(asr As IAsyncResult)
            Dim clientResult = CType(asr, XmlRpcAsyncResult)
            Dim proxy = CType(clientResult.ClientProtocol, ISearch)
            Dim userTuple = CType(clientResult.AsyncState, Tuple(Of Integer, Integer, Object))
            Try
                Dim asyncResult = proxy.EndGetCategories1(asr)
                Dim retval = Mapper.Map(Of XmlRpcStruct, IEnumerable(Of Category))(asyncResult)
                SetResultInCache(Of IEnumerable(Of Category))("GetRepresentativeCategories", retval, Me.Authentication, userTuple.Item1, userTuple.Item2)

                OnGetRepresentativeCategoriesCompleted(New GetRepresentativeCategoriesCompletedEventArgs() With {.Error = Nothing,
                                                                                                                .Result = True,
                                                                                                                .Categories = retval,
                                                                                                                .UserState = userTuple.Item3})
            Catch ex As Exception
                If TypeOf ex Is XmlRpcFaultException Then
                    Dim xmlrpcEx = CType(ex, XmlRpcFaultException)
                    OnGetRepresentativeCategoriesCompleted(New GetRepresentativeCategoriesCompletedEventArgs() With {.Error = Mapper.Map(Of XmlRpcFaultException, [Error])(xmlrpcEx),
                                                                                                                     .Result = False,
                                                                                                                     .UserState = userTuple.Item3})
                Else
                    Throw
                End If
            End Try
        End Sub

        Protected Sub OnGetRepresentativeCategoriesCompleted(ByVal e As EventArgs.GetRepresentativeCategoriesCompletedEventArgs)
            RaiseEvent GetRepresentativeCategoriesCompleted(Me, e)
        End Sub

        Public Sub GetRepresentativeCategoriesAsync(ByVal languageId As Integer,
                                      userState As Object) Implements IPartnerService.GetRepresentativeCategoriesAsync
            GetRepresentativeCategoriesAsyncInternal(languageId, Nothing, userState)
        End Sub

        Public Sub GetRepresentativeCategoriesAsync(ByVal languageId As Integer,
                              idCategoryParent As Integer,
                              userState As Object) Implements IPartnerService.GetRepresentativeCategoriesAsync
            GetRepresentativeCategoriesAsyncInternal(languageId, idCategoryParent, userState)
        End Sub

        Protected Sub GetRepresentativeCategoriesAsyncInternal(languageId As Integer,
                                                 idCategoryParent As Integer?,
                                                 userState As Object)
            Try
                Dim result = GetResultFromCache(Of IEnumerable(Of Category))("GetRepresentativeCategories", Me.Authentication, languageId, idCategoryParent)
                If result Is Nothing Then
                    Dim idCatParent = 0
                    If idCategoryParent.HasValue Then
                        idCatParent = idCategoryParent.Value
                    End If
                    SearchProxy.BeginGetCategories1(Me.Authentication,
                                                    languageId,
                                                    idCatParent,
                                                    AddressOf GetRepresentativeCategoriesCallBack,
                                                    New Tuple(Of Integer, Integer, Object)(languageId, idCatParent, userState))
                Else
                    OnGetRepresentativeCategoriesCompleted(New GetRepresentativeCategoriesCompletedEventArgs() With {.Error = Nothing,
                                                                                                                     .Result = True,
                                                                                                                     .Categories = result,
                                                                                                                     .UserState = userState})
                End If
            Catch ex As Exception
                If TypeOf ex Is XmlRpcFaultException Then
                    Dim xmlrpcEx = CType(ex, XmlRpcFaultException)
                    OnGetRepresentativeCategoriesCompleted(New GetRepresentativeCategoriesCompletedEventArgs() With {.Error = Mapper.Map(Of XmlRpcFaultException, [Error])(xmlrpcEx),
                                                                                                                     .Result = False,
                                                                                                                     .UserState = userState})
                Else
                    Throw
                End If
            End Try
        End Sub

        Public Event GetRepresentativeCategoriesCompleted(ByVal sender As Object, ByVal e As GetRepresentativeCategoriesCompletedEventArgs) Implements IPartnerService.GetRepresentativeCategoriesCompleted

#End Region

#Region "GetConceptualCategories"
        ''' <summary>
        ''' This method returns childs of a parent category in fotolia Conceptual category system. 
        ''' This method could be used to display a part of the category system or the all tree. 
        ''' Fotolia categories system counts three levels
        ''' </summary>
        ''' <param name="languageId">The language id.</param>
        ''' <param name="idCategoryParent">The id category parent.</param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Function GetConceptualCategories(ByVal languageId As Integer,
                                                Optional ByVal idCategoryParent As Integer? = Nothing) As IEnumerable(Of Category) Implements IPartnerService.GetConceptualCategories
            Dim retVal As IEnumerable(Of Category) = Nothing
            Try
                Dim idParent As Integer = 0
                If idCategoryParent.HasValue Then
                    idParent = idCategoryParent.Value
                End If
                retVal = ExecuteQuery(Of IEnumerable(Of Category))("GetConceptualCategories",
                                                                    Function() SearchProxy.GetCategories2(Me.Authentication, languageId, idParent),
                                                                    Me.Authentication,
                                                                    languageId,
                                                                    idParent)
            Catch ex As Exception
                ManageException(ex)
            End Try
            Return retVal
        End Function

        Private Sub GetConceptualCategoriesCallBack(asr As IAsyncResult)
            Dim clientResult = CType(asr, XmlRpcAsyncResult)
            Dim proxy = CType(clientResult.ClientProtocol, ISearch)
            Dim userTuple = CType(clientResult.AsyncState, Tuple(Of Integer, Integer, Object))
            Try
                Dim asyncResult = proxy.EndGetCategories2(asr)
                Dim retval = Mapper.Map(Of XmlRpcStruct, IEnumerable(Of Category))(asyncResult)
                SetResultInCache(Of IEnumerable(Of Category))("GetConceptualCategories", retval, Me.Authentication, userTuple.Item1, userTuple.Item2)
                OnGetConceptualCategoriesCompleted(New GetConceptualCategoriesCompletedEventArgs() With {.Error = Nothing,
                                                                                                         .Result = True,
                                                                                                         .Categories = retval,
                                                                                                         .UserState = userTuple.Item3})

            Catch ex As Exception
                If TypeOf ex Is XmlRpcFaultException Then
                    Dim xmlrpcEx = CType(ex, XmlRpcFaultException)
                    OnGetConceptualCategoriesCompleted(New GetConceptualCategoriesCompletedEventArgs() With {.Error = Mapper.Map(Of XmlRpcFaultException, [Error])(xmlrpcEx),
                                                                                             .Result = False,
                                                                                             .UserState = userTuple.Item3})
                Else
                    Throw
                End If
            End Try
        End Sub

        Protected Sub OnGetConceptualCategoriesCompleted(ByVal e As EventArgs.GetConceptualCategoriesCompletedEventArgs)
            RaiseEvent GetConceptualCategoriesCompleted(Me, e)
        End Sub

        ''' <summary>
        ''' Gets the conceptual categories async.
        ''' </summary>
        ''' <param name="languageId">The language id.</param>
        ''' <param name="userState">State of the user.</param>
        ''' <remarks></remarks>
        Public Sub GetConceptualCategoriesAsync(ByVal languageId As Integer,
                                      userState As Object) Implements IPartnerService.GetConceptualCategoriesAsync
            GetConceptualCategoriesAsyncInternal(languageId, Nothing, userState)
        End Sub

        ''' <summary>
        ''' Gets the conceptual categories async.
        ''' </summary>
        ''' <param name="languageId">The language id.</param>
        ''' <param name="idCategoryParent">The id category parent.</param>
        ''' <param name="userState">State of the user.</param>
        ''' <remarks></remarks>
        Public Sub GetConceptualCategoriesAsync(ByVal languageId As Integer,
                              idCategoryParent As Integer,
                              userState As Object) Implements IPartnerService.GetConceptualCategoriesAsync
            GetConceptualCategoriesAsyncInternal(languageId, idCategoryParent, userState)
        End Sub

        Protected Sub GetConceptualCategoriesAsyncInternal(languageId As Integer,
                                                 idCategoryParent As Integer?,
                                                 userState As Object)
            Try
                Dim result = GetResultFromCache(Of IEnumerable(Of Category))("GetConceptualCategories", Me.Authentication, languageId, If(Not idCategoryParent.HasValue, 0, idCategoryParent.Value))
                If result Is Nothing Then
                    Dim idCatParent = 0
                    If idCategoryParent.HasValue Then
                        idCatParent = idCategoryParent.Value
                    End If

                    SearchProxy.BeginGetCategories2(Me.Authentication,
                                                    languageId,
                                                    idCatParent,
                                                    AddressOf GetConceptualCategoriesCallBack,
                                                    New Tuple(Of Integer, Integer, Object)(languageId, idCatParent, userState))
                Else
                    OnGetConceptualCategoriesCompleted(New GetConceptualCategoriesCompletedEventArgs() With {.Error = Nothing,
                                                                                                            .Result = True,
                                                                                                            .Categories = result,
                                                                                                             .UserState = userState})
                End If
            Catch ex As Exception
                If TypeOf ex Is XmlRpcFaultException Then
                    Dim xmlrpcEx = CType(ex, XmlRpcFaultException)
                    OnGetConceptualCategoriesCompleted(New GetConceptualCategoriesCompletedEventArgs() With {.Error = Mapper.Map(Of XmlRpcFaultException, [Error])(xmlrpcEx),
                                                                                                                         .Result = False,
                                                                                                                         .UserState = userState})
                Else
                    Throw
                End If
            End Try
        End Sub

        ''' <summary>
        ''' Occurs when [get categories completed].
        ''' </summary>
        ''' <remarks></remarks>
        Public Event GetConceptualCategoriesCompleted(ByVal sender As Object, ByVal e As GetConceptualCategoriesCompletedEventArgs) Implements IPartnerService.GetConceptualCategoriesCompleted

#End Region

#Region "GetTags"
        ''' <summary>
        ''' This method returns most searched tag and most used tag on fotolia website.
        ''' This method may help you to create a tags cloud.
        ''' </summary>
        ''' <param name="languageId">The language id.</param>
        ''' <param name="tagType">Type of the tag:
        ''' <see cref="Fttk.Entities.TagType.Used">TagType.Used</see> : Most used tags to index media
        ''' <see cref="Fttk.Entities.TagType.Searched">TagType.Searched</see> : Most used tags to search for media</param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Function GetTags(ByVal languageId As Integer, ByVal tagType As TagType) As IEnumerable(Of Tag) Implements IPartnerService.GetTags
            Dim retVal As IEnumerable(Of Tag) = Nothing
            Try
                retVal = ExecuteQuery(Of IEnumerable(Of Tag))("GetTags",
                                                                Function() SearchProxy.GetTags(Me.Authentication, languageId, TagTypes.GetTypeString(tagType)),
                                                                Me.Authentication,
                                                                languageId,
                                                                tagType)
            Catch ex As Exception
                ManageException(ex)
            End Try
            Return retVal
        End Function

        ''' <summary>
        ''' This method returns most searched tag and most used tag on fotolia website.
        ''' This method may help you to create a tags cloud.
        ''' </summary>
        ''' <param name="languageId">The language id.</param>
        ''' <param name="tagType">Type of the tag:
        ''' <see cref="Fttk.Entities.TagType.Used">TagType.Used</see> : Most used tags to index media
        ''' <see cref="Fttk.Entities.TagType.Searched">TagType.Searched</see> : Most used tags to search for media</param>
        ''' <param name="userState">The user state.</param>
        ''' <remarks></remarks>
        Public Sub GetTagsAsync(ByVal languageId As Integer, ByVal tagType As TagType, ByVal userState As Object) Implements IPartnerService.GetTagsAsync
            Try
                Dim strTagType = TagTypes.GetTypeString(tagType)
                Dim result = GetResultFromCache(Of IEnumerable(Of Tag))("GetTags", Me.Authentication, languageId, tagType)
                If result Is Nothing Then
                    SearchProxy.BeginGetTags(Me.Authentication, languageId, strTagType,
                                             AddressOf GetTagsCallBack, New Tuple(Of Integer, TagType, Object)(languageId, tagType, userState))
                Else
                    OnGetTagsCompleted(New GetTagsCompletedEventArgs() With {.Error = Nothing,
                                                                            .Result = True,
                                                                            .Tags = result,
                                                                            .UserState = userState})
                End If
            Catch ex As Exception
                If TypeOf ex Is XmlRpcFaultException Then
                    Dim xmlrpcEx = CType(ex, XmlRpcFaultException)
                    OnGetTagsCompleted(New GetTagsCompletedEventArgs() With {.Error = Mapper.Map(Of XmlRpcFaultException, [Error])(xmlrpcEx),
                                                                                .Result = False,
                                                                                .UserState = userState})
                Else
                    Throw
                End If
            End Try
        End Sub

        Private Sub GetTagsCallBack(asr As IAsyncResult)
            Dim clientResult = CType(asr, XmlRpcAsyncResult)
            Dim proxy = CType(clientResult.ClientProtocol, ISearch)
            Dim userTuple = CType(clientResult.AsyncState, Tuple(Of Integer, TagType, Object))
            Try
                Dim asyncResult = proxy.EndGetTags(asr)
                Dim retval = Mapper.Map(Of XmlRpcStruct(), IEnumerable(Of Entities.Tag))(asyncResult)
                SetResultInCache(Of IEnumerable(Of Tag))("GetTags", retval, Me.Authentication, userTuple.Item1, userTuple.Item2)
                OnGetTagsCompleted(New GetTagsCompletedEventArgs() With {.Error = Nothing,
                                                                            .Result = True,
                                                                            .Tags = retval,
                                                                            .UserState = userTuple.Item3})
            Catch ex As Exception
                If TypeOf ex Is XmlRpcFaultException Then
                    Dim xmlrpcEx = CType(ex, XmlRpcFaultException)
                    OnGetTagsCompleted(New GetTagsCompletedEventArgs() With {.Error = Mapper.Map(Of XmlRpcFaultException, [Error])(xmlrpcEx),
                                                                                .Result = False,
                                                                                .UserState = userTuple.Item3})
                Else
                    Throw
                End If
            End Try
        End Sub

        Public Event GetTagsCompleted(ByVal sender As Object, ByVal e As GetTagsCompletedEventArgs) Implements IPartnerService.GetTagsCompleted

        Protected Sub OnGetTagsCompleted(getTagsCompletedEventArgs As GetTagsCompletedEventArgs)
            RaiseEvent GetTagsCompleted(Me, getTagsCompletedEventArgs)
        End Sub

#End Region

#Region "GetGalleries"

        ''' <summary>
        ''' This methods returns public galleries for a defined language
        ''' </summary>
        ''' <param name="languageId">The language id.</param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Function GetGalleries(ByVal languageId As Integer) As IEnumerable(Of Gallery) Implements IPartnerService.GetGalleries
            Dim retVal As IEnumerable(Of Gallery) = Nothing
            Try
                retVal = ExecuteQuery(Of IEnumerable(Of Gallery))("GetGalleries",
                                                                Function() SearchProxy.GetGalleries(Me.Authentication, languageId),
                                                                Me.Authentication,
                                                                languageId)
            Catch ex As Exception
                ManageException(ex)
            End Try
            Return retVal
        End Function

        ''' <summary>
        ''' This methods returns public galleries for a defined language in async mode.
        ''' </summary>
        ''' <param name="languageId">The language id.</param>
        ''' <param name="userState">The user state.</param>
        ''' <remarks></remarks>
        Public Sub GetGalleriesAsync(ByVal languageId As Integer, ByVal userState As Object) Implements IPartnerService.GetGalleriesAsync
            Try
                Dim result = GetResultFromCache(Of IEnumerable(Of Gallery))("GetGalleries", Me.Authentication, languageId)
                If result Is Nothing Then
                    SearchProxy.BeginGetGalleries(Me.Authentication,
                                                    languageId,
                                                    AddressOf GetGalleriesCallBack,
                                                    New Tuple(Of Integer, Object)(languageId, userState))
                Else
                    OnGetGalleriesCompleted(New GetGalleriesCompletedEventArgs() With {.Error = Nothing,
                                                                            .Result = True,
                                                                            .Galleries = result,
                                                                            .UserState = userState})
                End If
            Catch ex As Exception
                If TypeOf ex Is XmlRpcFaultException Then
                    Dim xmlrpcEx = CType(ex, XmlRpcFaultException)
                    OnGetTagsCompleted(New GetTagsCompletedEventArgs() With {.Error = Mapper.Map(Of XmlRpcFaultException, [Error])(xmlrpcEx),
                                                                                .Result = False,
                                                                                .UserState = userState})
                Else
                    Throw
                End If
            End Try
        End Sub

        Private Sub GetGalleriesCallBack(asr As IAsyncResult)
            Dim clientResult = CType(asr, XmlRpcAsyncResult)
            Dim proxy = CType(clientResult.ClientProtocol, ISearch)
            Dim userTuple = CType(clientResult.AsyncState, Tuple(Of Integer, Object))
            Try
                Dim asyncResult = proxy.EndGetGalleries(asr)
                Dim retval = Mapper.Map(Of XmlRpcStruct(), IEnumerable(Of Entities.Gallery))(asyncResult)
                SetResultInCache(Of IEnumerable(Of Gallery))("GetGalleries", retval, Me.Authentication, userTuple.Item1)
                OnGetGalleriesCompleted(New GetGalleriesCompletedEventArgs() With {.Error = Nothing,
                                                                            .Result = True,
                                                                            .Galleries = retval,
                                                                            .UserState = userTuple.Item2})
            Catch ex As Exception
                If TypeOf ex Is XmlRpcFaultException Then
                    Dim xmlrpcEx = CType(ex, XmlRpcFaultException)
                    OnGetGalleriesCompleted(New GetGalleriesCompletedEventArgs() With {.Error = Mapper.Map(Of XmlRpcFaultException, [Error])(xmlrpcEx),
                                                                                .Result = False,
                                                                                .UserState = userTuple.Item2})
                Else
                    Throw
                End If
            End Try
        End Sub

        Public Event GetGalleriesCompleted(ByVal sender As Object, ByVal e As GetGalleriesCompletedEventArgs) Implements IPartnerService.GetGalleriesCompleted

        Protected Sub OnGetGalleriesCompleted(e As GetGalleriesCompletedEventArgs)
            RaiseEvent GetGalleriesCompleted(Me, e)
        End Sub
#End Region

#Region "GetColors"

        ''' <summary>
        ''' This method returns childs of a parent colors in the Fotolia color scheme.
        ''' If no parent is provided first level colors are returned.
        ''' This method can be used to display color and subcolors for color search queries.
        ''' </summary>
        ''' <param name="idColorParent">The id color parent.</param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Function GetColors(Optional ByVal idColorParent As Integer? = Nothing) As IEnumerable(Of Color) Implements IPartnerService.GetColors
            Dim retVal As IEnumerable(Of Color) = Nothing
            Try
                Dim colorParent = If(Not idColorParent.HasValue, 0, idColorParent.Value)
                retVal = ExecuteQuery(Of IEnumerable(Of Color))("GetColors",
                                                                  Function()
                                                                      Dim result = SearchProxy.GetColors(Me.Authentication, colorParent)
                                                                      If result.ContainsKey("colors") Then
                                                                          Return CType(result.Item("colors"), XmlRpcStruct)
                                                                      Else
                                                                          Throw New FotoliaException("Incorrect Xml-Rpc format from server!")
                                                                      End If
                                                                  End Function,
                                                                Me.Authentication,
                                                                colorParent)
            Catch ex As Exception
                ManageException(ex)
            End Try
            Return retVal
        End Function

        ''' <summary>
        ''' This method returns childs of a parent colors in the Fotolia color scheme in async mode.
        ''' If no parent is provided first level colors are returned.
        ''' This method can be used to display color and subcolors for color search queries.
        ''' </summary>
        ''' <param name="idColorParent">The id color parent.</param>
        ''' <param name="userState">State of the user.</param>
        ''' <remarks></remarks>
        Public Sub GetColorsAsync(ByVal idColorParent As Integer, ByVal userState As Object) Implements IPartnerService.GetColorsAsync
            Try
                Dim result = GetResultFromCache(Of IEnumerable(Of Color))("GetColors", Me.Authentication, idColorParent)
                If result Is Nothing Then
                    SearchProxy.BeginGetColors(Me.Authentication,
                                                idColorParent,
                                                AddressOf GetColorsCallBack,
                                                New Tuple(Of Integer, Object)(idColorParent, userState))
                Else
                    OnGetColorsCompleted(New GetColorsCompletedEventArgs() With {.Error = Nothing,
                                                                            .Result = True,
                                                                            .Colors = result,
                                                                            .UserState = userState})
                End If
            Catch ex As Exception
                If TypeOf ex Is XmlRpcFaultException Then
                    Dim xmlrpcEx = CType(ex, XmlRpcFaultException)
                    OnGetColorsCompleted(New GetColorsCompletedEventArgs() With {.Error = Mapper.Map(Of XmlRpcFaultException, [Error])(xmlrpcEx),
                                                                                .Result = False,
                                                                                .UserState = userState})
                Else
                    Throw
                End If
            End Try
        End Sub

        ''' <summary>
        ''' This method returns childs of a parent colors in the Fotolia color scheme in async mode.
        ''' If no parent is provided first level colors are returned.
        ''' This method can be used to display color and subcolors for color search queries.
        ''' </summary>
        ''' <param name="userState">State of the user.</param>
        ''' <remarks></remarks>
        Public Sub GetColorsAsync(ByVal userState As Object) Implements IPartnerService.GetColorsAsync
            Try
                Dim result = GetResultFromCache(Of IEnumerable(Of Color))("GetColors", Me.Authentication, 0)
                If result Is Nothing Then
                    SearchProxy.BeginGetColors(Me.Authentication,
                                                0,
                                                AddressOf GetColorsCallBack,
                                                New Tuple(Of Integer, Object)(0, userState))
                Else
                    OnGetColorsCompleted(New GetColorsCompletedEventArgs() With {.Error = Nothing,
                                                                            .Result = True,
                                                                            .Colors = result,
                                                                            .UserState = userState})
                End If
            Catch ex As Exception
                If TypeOf ex Is XmlRpcFaultException Then
                    Dim xmlrpcEx = CType(ex, XmlRpcFaultException)
                    OnGetColorsCompleted(New GetColorsCompletedEventArgs() With {.Error = Mapper.Map(Of XmlRpcFaultException, [Error])(xmlrpcEx),
                                                                                .Result = False,
                                                                                .UserState = userState})
                Else
                    Throw
                End If
            End Try
        End Sub

        Private Sub GetColorsCallBack(asr As IAsyncResult)
            Dim clientResult = CType(asr, XmlRpcAsyncResult)
            Dim proxy = CType(clientResult.ClientProtocol, ISearch)
            Dim userTuple = CType(clientResult.AsyncState, Tuple(Of Integer, Object))
            Try
                Dim asyncResult = proxy.EndGetColors(asr)
                If asyncResult.ContainsKey("colors") Then
                    Dim retval = Mapper.Map(Of XmlRpcStruct, IEnumerable(Of Entities.Color))(CType(asyncResult.Item("colors"), XmlRpcStruct))

                    OnGetColorsCompleted(New GetColorsCompletedEventArgs() With {.Error = Nothing,
                                                                                .Result = True,
                                                                                .Colors = retval,
                                                                                .UserState = userTuple.Item2})
                Else
                    Throw New FotoliaException("Incorrect Xml-Rpc format from server!")
                End If
            Catch ex As Exception
                If TypeOf ex Is XmlRpcFaultException Then
                    Dim xmlrpcEx = CType(ex, XmlRpcFaultException)
                    OnGetColorsCompleted(New GetColorsCompletedEventArgs() With {.Error = Mapper.Map(Of XmlRpcFaultException, [Error])(xmlrpcEx),
                                                                                .Result = False,
                                                                                .UserState = userTuple.Item2})
                Else
                    Throw
                End If
            End Try
        End Sub

        ''' <summary>
        ''' Occurs when [get colors completed].
        ''' </summary>
        ''' <remarks></remarks>
        Public Event GetColorsCompleted(ByVal sender As Object, ByVal e As GetColorsCompletedEventArgs) Implements IPartnerService.GetColorsCompleted

        Protected Sub OnGetColorsCompleted(e As GetColorsCompletedEventArgs)
            RaiseEvent GetColorsCompleted(Me, e)
        End Sub
#End Region

#Region "GetCountries"
        ''' <summary>
        ''' This method returns Fotolia list of countries.
        ''' </summary>
        ''' <param name="languageId">The language id.</param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Function GetCountries(ByVal languageId As Integer) As IEnumerable(Of Country) Implements IPartnerService.GetCountries
            Dim retVal As IEnumerable(Of Country) = Nothing
            Try
                retVal = ExecuteQuery(Of IEnumerable(Of Country))("GetCountries",
                                                               Function() SearchProxy.GetCountries(Me.Authentication, languageId),
                                                               Me.Authentication,
                                                               languageId)
            Catch ex As Exception
                ManageException(ex)
            End Try
            Return retVal
        End Function

        ''' <summary>
        ''' This method returns Fotolia list of countries in async mode.
        ''' </summary>
        ''' <param name="languageId">The language id.</param>
        ''' <param name="userState">User state.</param>
        ''' <remarks></remarks>
        Public Sub GetCountriesAsync(ByVal languageId As Integer, ByVal userState As Object) Implements IPartnerService.GetCountriesAsync
            Try
                Dim result = GetResultFromCache(Of IEnumerable(Of Country))("GetCountries", Me.Authentication, languageId)
                If result Is Nothing Then
                    SearchProxy.BeginGetCountries(Me.Authentication, _
                                                  languageId, _
                                                  AddressOf GetCountriesCallBack, _
                                                  New Tuple(Of Integer, Object)(languageId, userState))
                Else
                    OnGetCountriesCompleted(New GetCountriesCompletedEventArgs() With {.Error = Nothing,
                                                                                       .Result = True,
                                                                                       .Countries = result,
                                                                                       .UserState = userState})
                End If
            Catch ex As Exception
                If TypeOf ex Is XmlRpcFaultException Then
                    Dim xmlrpcEx = CType(ex, XmlRpcFaultException)
                    OnGetCountriesCompleted(New GetCountriesCompletedEventArgs() With {.Error = Mapper.Map(Of XmlRpcFaultException, [Error])(xmlrpcEx),
                                                                                       .Result = False,
                                                                                       .UserState = userState})
                Else
                    Throw
                End If
            End Try
        End Sub

        Private Sub GetCountriesCallBack(asr As IAsyncResult)
            Dim clientResult = CType(asr, XmlRpcAsyncResult)
            Dim proxy = CType(clientResult.ClientProtocol, ISearch)
            Dim userTuple = CType(clientResult.AsyncState, Tuple(Of Integer, Object))
            Try
                Dim asyncResult = proxy.EndGetCountries(asr)
                Dim retval = Mapper.Map(Of XmlRpcStruct(), IEnumerable(Of Entities.Country))(asyncResult)

                OnGetCountriesCompleted(New GetCountriesCompletedEventArgs() With {.Error = Nothing,
                                                                                    .Result = True,
                                                                                    .Countries = retval,
                                                                                    .UserState = userTuple.Item2})
            Catch ex As Exception
                If TypeOf ex Is XmlRpcFaultException Then
                    Dim xmlrpcEx = CType(ex, XmlRpcFaultException)
                    OnGetCountriesCompleted(New GetCountriesCompletedEventArgs() With {.Error = Mapper.Map(Of XmlRpcFaultException, [Error])(xmlrpcEx),
                                                                                        .Result = False,
                                                                                        .UserState = userTuple.Item2})
                Else
                    Throw
                End If
            End Try
        End Sub

        ''' <summary>
        ''' Occurs when [get countries completed].
        ''' </summary>
        ''' <remarks></remarks>
        Public Event GetCountriesCompleted(ByVal sender As Object, ByVal e As GetCountriesCompletedEventArgs) Implements IPartnerService.GetCountriesCompleted

        Protected Sub OnGetCountriesCompleted(e As GetCountriesCompletedEventArgs)
            RaiseEvent GetCountriesCompleted(Me, e)
        End Sub
#End Region

#Region "GetSearchResults"

        ''' <summary>
        ''' This methods makes possible to search media in fotolia image bank. Full search capabilities are available through the API.
        ''' </summary>
        ''' <param name="request">The search request.</param>
        ''' <param name="numberOfResults">Total number of media that verify search parameters.</param>
        ''' <param name="columns">The desires columns in results collection.</param>
        ''' <param name="useCache">If True, the search use data in cache (if it is present), otherwise, the method makes the web request. By default the value is false.</param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Function GetSearchResults(ByVal request As Entities.SearchRequest,
                                         ByRef numberOfResults As Integer,
                                         Optional columns As SearchResultsColumns = SearchResultsColumns.Base,
                                         Optional useCache As Boolean = False) As IEnumerable(Of Media) Implements IPartnerService.GetSearchResults
            Dim retVal As IEnumerable(Of Media) = Nothing
            Try
                If useCache Then
                    Dim cacheValue = GetResultFromCache(Of Tuple(Of IEnumerable(Of Media), Integer))("GetSearchResults", request, columns)
                    If cacheValue IsNot Nothing Then
                        retVal = cacheValue.Item1
                        numberOfResults = cacheValue.Item2
                    End If
                End If

                If retVal Is Nothing Then
                    Dim searchParameters = Mapper.Map(Of Entities.SearchRequest, FTTK.XmlRpc.SearchRequest)(request)
                    Dim result = SearchProxy.GetSearchResults(Me.Authentication, searchParameters, FTTK.XmlRpc.SearchResultColumns.FromEntityColumns(columns))
                    numberOfResults = result.GetValueOrDefault(Of Integer)("nb_results", -1)

                    retVal = Mapper.Map(Of XmlRpcStruct(), IEnumerable(Of Media))(result.Values.OfType(Of XmlRpcStruct).ToArray())

                    SetResultInCache(Of Tuple(Of IEnumerable(Of Media), Integer))("GetSearchResults", New Tuple(Of IEnumerable(Of Media), Integer)(retVal, numberOfResults), request, columns)
                End If

            Catch ex As Exception
                ManageException(ex)
            End Try
            Return retVal
        End Function

        ''' <summary>
        ''' This methods makes possible to search media in fotolia image bank. Full search capabilities are available through the API.
        ''' </summary>
        ''' <param name="request">The search request.</param>
        ''' <param name="userState">User state.</param>
        ''' <remarks></remarks>
        Public Sub GetSearchResultsAsync(ByVal request As Entities.SearchRequest,
                                         ByVal userState As Object,
                                         Optional useCache As Boolean = False) Implements IPartnerService.GetSearchResultsAsync
            GetSearchResultsAsync(request, SearchResultsColumns.Base, userState, useCache)
        End Sub

        ''' <summary>
        ''' This methods makes possible to search media in fotolia image bank. Full search capabilities are available through the API.
        ''' </summary>
        ''' <param name="request">The search request.</param>
        ''' <param name="columns">The desires columns in results collection.</param>
        ''' <param name="userState">user state.</param>
        ''' <remarks></remarks>
        Public Sub GetSearchResultsAsync(ByVal request As Entities.SearchRequest,
                                         ByVal columns As SearchResultsColumns,
                                         ByVal userState As Object,
                                         Optional useCache As Boolean = False) Implements IPartnerService.GetSearchResultsAsync
            Try
                Dim result As IEnumerable(Of Media) = Nothing
                Dim numberOfResults As Integer = -1
                If useCache Then
                    Dim cacheValue = GetResultFromCache(Of Tuple(Of IEnumerable(Of Media), Integer))("GetSearchResults", request, columns)
                    If cacheValue IsNot Nothing Then
                        result = cacheValue.Item1
                        numberOfResults = cacheValue.Item2
                    End If
                End If
                If result Is Nothing Then
                    Dim searchParameters = Mapper.Map(Of Entities.SearchRequest, FTTK.XmlRpc.SearchRequest)(request)
                    Dim searchColumns = FTTK.XmlRpc.SearchResultColumns.FromEntityColumns(columns)
                    SearchProxy.BeginGetSearchResults(Me.Authentication,
                                                        searchParameters,
                                                        searchColumns,
                                                        AddressOf GetSearchResultsCallBack,
                                                        New Tuple(Of Entities.SearchRequest, SearchResultsColumns, Object)(request, columns, userState))
                Else
                    OnGetSearchResultsCompleted(New GetSearchResultsCompletedEventArgs() With {.Error = Nothing,
                                                                                           .Result = True,
                                                                                           .MediaList = result,
                                                                                           .NumberOfResults = numberOfResults,
                                                                                           .UserState = userState})
                End If
            Catch ex As Exception
                If TypeOf ex Is XmlRpcFaultException Then
                    Dim xmlrpcEx = CType(ex, XmlRpcFaultException)
                    OnGetSearchResultsCompleted(New GetSearchResultsCompletedEventArgs() With {.Error = Mapper.Map(Of XmlRpcFaultException, [Error])(xmlrpcEx),
                                                                                        .Result = False,
                                                                                        .UserState = userState})
                Else
                    Throw
                End If
            End Try
        End Sub

        Private Sub GetSearchResultsCallBack(asr As IAsyncResult)
            Dim clientResult = CType(asr, XmlRpcAsyncResult)
            Dim proxy = CType(clientResult.ClientProtocol, ISearch)
            Dim userTuple = CType(clientResult.AsyncState, Tuple(Of Entities.SearchRequest, SearchResultsColumns, Object))
            Try
                Dim asyncResult = proxy.EndGetSearchResults(asr)

                Dim numberOfResults = asyncResult.GetValueOrDefault(Of Integer)("nb_results", -1)

                Dim retlist = Mapper.Map(Of XmlRpcStruct(), IEnumerable(Of Media))(asyncResult.Values.OfType(Of XmlRpcStruct).ToArray())

                SetResultInCache(Of Tuple(Of IEnumerable(Of Media), Integer))("GetSearchResults",
                                                                              New Tuple(Of IEnumerable(Of Media), Integer)(retlist, numberOfResults),
                                                                              userTuple.Item1, userTuple.Item2)

                OnGetSearchResultsCompleted(New GetSearchResultsCompletedEventArgs() With {.Error = Nothing,
                                                                                           .Result = True,
                                                                                           .MediaList = retlist,
                                                                                           .NumberOfResults = numberOfResults,
                                                                                           .UserState = userTuple.Item3})
            Catch ex As Exception
                If TypeOf ex Is XmlRpcFaultException Then
                    Dim xmlrpcEx = CType(ex, XmlRpcFaultException)
                    OnGetSearchResultsCompleted(New GetSearchResultsCompletedEventArgs() With {.Error = Mapper.Map(Of XmlRpcFaultException, [Error])(xmlrpcEx),
                                                                                        .Result = False,
                                                                                        .UserState = userTuple.Item3})
                Else
                    Throw
                End If
            End Try
        End Sub

        ''' <summary>
        ''' Occurs when [get search results completed].
        ''' </summary>
        ''' <remarks></remarks>
        Public Event GetSearchResultsCompleted(ByVal sender As Object, ByVal e As GetSearchResultsCompletedEventArgs) Implements IPartnerService.GetSearchResultsCompleted

        Protected Sub OnGetSearchResultsCompleted(e As GetSearchResultsCompletedEventArgs)
            RaiseEvent GetSearchResultsCompleted(Me, e)
        End Sub
#End Region

#Region "GetMediaData"

        ''' <summary>
        ''' This method return all information about a media.
        ''' </summary>
        ''' <param name="mediaId">Media id.</param>
        ''' <param name="languageId">Language Id.</param>
        ''' <param name="thumbnailSize">Thumbnail size.</param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Function GetMediaData(ByVal mediaId As Integer,
                                     ByVal languageId As Integer,
                                     ByVal thumbnailSize As Entities.SearchThumbnailSize) As Media Implements IPartnerService.GetMediaData
            Dim retVal As Media = Nothing
            Try
                retVal = ExecuteQuery(Of Media)("GetMediaData",
                                                Function() MediaDataProxy.GetMediaData(Me.Authentication, mediaId, FTTK.XmlRpc.SearchThumbnailSize.FromEntitySize(thumbnailSize), languageId),
                                                Me.Authentication,
                                                mediaId,
                                                languageId,
                                                thumbnailSize)
            Catch ex As Exception
                ManageException(ex)
            End Try
            Return retVal
        End Function

        ''' <summary>
        ''' This method return all information about a media in async mode.
        ''' </summary>
        ''' <param name="mediaId">Media id.</param>
        ''' <param name="languageId">Language Id.</param>
        ''' <param name="thumbnailSize">Thumbnail size.</param>
        ''' <param name="userState">The user state object.</param>
        ''' <remarks></remarks>
        Public Sub GetMediaDataAsync(ByVal mediaId As Integer,
                                     ByVal languageId As Integer,
                                     ByVal thumbnailSize As Entities.SearchThumbnailSize,
                                     ByVal userState As Object) Implements IPartnerService.GetMediaDataAsync
            Try
                Dim result = GetResultFromCache(Of Media)("GetMediaData", Me.Authentication, mediaId, languageId, thumbnailSize)
                If result Is Nothing Then
                    MediaDataProxy.BeginGetMediaData(Me.Authentication,
                                                    mediaId,
                                                    FTTK.XmlRpc.SearchThumbnailSize.FromEntitySize(thumbnailSize),
                                                    languageId,
                                                    AddressOf GetMediaDataCallBack,
                                                    New Tuple(Of Integer, Integer, Entities.SearchThumbnailSize, Object)(mediaId, languageId, thumbnailSize, userState))
                Else
                    OnGetMediaDataCompleted(New GetMediaDataCompletedEventArgs() With {.Error = Nothing,
                                                                                        .Result = True,
                                                                                        .Media = result,
                                                                                        .UserState = userState})
                End If
            Catch ex As Exception
                If TypeOf ex Is XmlRpcFaultException Then
                    Dim xmlrpcEx = CType(ex, XmlRpcFaultException)
                    OnGetMediaDataCompleted(New GetMediaDataCompletedEventArgs() With {.Error = Mapper.Map(Of XmlRpcFaultException, [Error])(xmlrpcEx),
                                                                                        .Result = False,
                                                                                        .UserState = userState})
                Else
                    Throw
                End If
            End Try
        End Sub

        Private Sub GetMediaDataCallBack(asr As IAsyncResult)
            Dim clientResult = CType(asr, XmlRpcAsyncResult)
            Dim proxy = CType(clientResult.ClientProtocol, IMediaData)
            Dim userTuple = CType(clientResult.AsyncState, Tuple(Of Integer, Integer, Entities.SearchThumbnailSize, Object))
            Try
                Dim asyncResult = proxy.EndGetMediaData(asr)
                Dim media = Mapper.Map(Of XmlRpcStruct, Media)(asyncResult)
                SetResultInCache(Of Media)("GetMediaData", media, Me.Authentication, userTuple.Item1, userTuple.Item2, userTuple.Item3)
                OnGetMediaDataCompleted(New GetMediaDataCompletedEventArgs() With {.Error = Nothing,
                                                                                    .Result = True,
                                                                                    .Media = media,
                                                                                    .UserState = userTuple.Item4})
            Catch ex As Exception
                If TypeOf ex Is XmlRpcFaultException Then
                    Dim xmlrpcEx = CType(ex, XmlRpcFaultException)
                    OnGetMediaDataCompleted(New GetMediaDataCompletedEventArgs() With {.Error = Mapper.Map(Of XmlRpcFaultException, [Error])(xmlrpcEx),
                                                                                        .Result = False,
                                                                                        .UserState = userTuple.Item4})
                Else
                    Throw
                End If
            End Try
        End Sub

        ''' <summary>
        ''' Occurs when [get media data completed].
        ''' </summary>
        ''' <remarks></remarks>
        Public Event GetMediaDataCompleted(ByVal sender As Object, ByVal e As GetMediaDataCompletedEventArgs) Implements IPartnerService.GetMediaDataCompleted

        Protected Sub OnGetMediaDataCompleted(e As GetMediaDataCompletedEventArgs)
            RaiseEvent GetMediaDataCompleted(Me, e)
        End Sub
#End Region

#Region "GetMediaGalleries"

        ''' <summary>
        ''' This methods return galleries associated to a media.
        ''' </summary>
        ''' <param name="mediaId">Media id.</param>
        ''' <param name="languageId">Language Id.</param>
        ''' <param name="thumbnailSize">Thumbnail size.</param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Function GetMediaGalleries(ByVal mediaId As Integer,
                                          ByVal languageId As Integer,
                                          ByVal thumbnailSize As Entities.SearchThumbnailSize) As IEnumerable(Of Gallery) Implements IPartnerService.GetMediaGalleries
            Dim retVal As IEnumerable(Of Gallery) = Nothing
            Try
                retVal = ExecuteQuery(Of IEnumerable(Of Gallery))("GetMediaGalleries",
                                                                  Function() MediaDataProxy.GetMediaGalleries(Me.Authentication, mediaId, languageId, FTTK.XmlRpc.SearchThumbnailSize.FromEntitySize(thumbnailSize)),
                                                                  Me.Authentication,
                                                                  mediaId,
                                                                  languageId,
                                                                  thumbnailSize)
            Catch ex As Exception
                ManageException(ex)
            End Try
            Return retVal
        End Function

        ''' <summary>
        ''' This methods return galleries associated to a media in async mode.
        ''' </summary>
        ''' <param name="mediaId">Media id.</param>
        ''' <param name="languageId">Language Id.</param>
        ''' <param name="thumbnailSize">Thumbnail size.</param>
        ''' <param name="userState">The user state object.</param>
        ''' <remarks></remarks>
        Public Sub GetMediaGalleriesAsync(ByVal mediaId As Integer, ByVal languageId As Integer, ByVal thumbnailSize As Entities.SearchThumbnailSize, ByVal userState As Object) Implements IPartnerService.GetMediaGalleriesAsync
            Try
                Dim result = GetResultFromCache(Of IEnumerable(Of Gallery))("GetMediaGalleries", Me.Authentication, mediaId, languageId, thumbnailSize)
                If result Is Nothing Then
                    MediaDataProxy.BeginGetMediaGalleries(Me.Authentication,
                                                          mediaId,
                                                          languageId,
                                                          FTTK.XmlRpc.SearchThumbnailSize.FromEntitySize(thumbnailSize),
                                                          AddressOf GetMediaGalleriesCallBack,
                                                          New Tuple(Of Integer, Integer, Entities.SearchThumbnailSize, Object)(mediaId, languageId, thumbnailSize, userState))
                Else
                    OnGetMediaGalleriesCompleted(New GetMediaGalleriesCompletedEventArgs() With {.Error = Nothing,
                                                                                                 .Result = True,
                                                                                                 .Galleries = result,
                                                                                                 .MediaId = mediaId,
                                                                                                 .UserState = userState})
                End If
            Catch ex As Exception
                If TypeOf ex Is XmlRpcFaultException Then
                    Dim xmlrpcEx = CType(ex, XmlRpcFaultException)
                    OnGetMediaGalleriesCompleted(New GetMediaGalleriesCompletedEventArgs() With {.Error = Mapper.Map(Of XmlRpcFaultException, [Error])(xmlrpcEx),
                                                                                                 .Result = False,
                                                                                                 .UserState = userState,
                                                                                                 .MediaId = mediaId})
                Else
                    Throw
                End If
            End Try
        End Sub

        Private Sub GetMediaGalleriesCallBack(asr As IAsyncResult)
            Dim clientResult = CType(asr, XmlRpcAsyncResult)
            Dim proxy = CType(clientResult.ClientProtocol, IMediaData)
            Dim userTuple = CType(clientResult.AsyncState, Tuple(Of Integer, Integer, Entities.SearchThumbnailSize, Object))
            Try
                Dim asyncResult = proxy.EndGetMediaGalleries(asr)
                Dim galleries = Mapper.Map(Of XmlRpcStruct(), IEnumerable(Of Gallery))(asyncResult)
                SetResultInCache(Of IEnumerable(Of Gallery))("GetMediaGalleries", galleries, Me.Authentication, userTuple.Item1, userTuple.Item2, userTuple.Item3)
                OnGetMediaGalleriesCompleted(New GetMediaGalleriesCompletedEventArgs() With {.Error = Nothing,
                                                                                            .Result = True,
                                                                                            .Galleries = galleries,
                                                                                            .MediaId = userTuple.Item1,
                                                                                            .UserState = userTuple.Item4})
            Catch ex As Exception
                If TypeOf ex Is XmlRpcFaultException Then
                    Dim xmlrpcEx = CType(ex, XmlRpcFaultException)
                    OnGetMediaGalleriesCompleted(New GetMediaGalleriesCompletedEventArgs() With {.Error = Mapper.Map(Of XmlRpcFaultException, [Error])(xmlrpcEx),
                                                                                                .Result = False,
                                                                                                .MediaId = userTuple.Item1,
                                                                                                .UserState = userTuple.Item4})
                Else
                    Throw
                End If
            End Try
        End Sub

        ''' <summary>
        ''' Occurs when [get media galleries completed].
        ''' </summary>
        ''' <remarks></remarks>
        Public Event GetMediaGalleriesCompleted(ByVal sender As Object, ByVal e As GetMediaGalleriesCompletedEventArgs) Implements IPartnerService.GetMediaGalleriesCompleted

        Protected Sub OnGetMediaGalleriesCompleted(e As GetMediaGalleriesCompletedEventArgs)
            RaiseEvent GetMediaGalleriesCompleted(Me, e)
        End Sub
#End Region

#Region "GetMediaComp"
        ''' <summary>
        ''' This method returns comp images.
        ''' Comp images can ONLY be used to evaluate the image as to suitability for a project, obtain client or internal company approvals, or experiment with layout alternatives.
        ''' </summary>
        ''' <param name="mediaId">Media ID (ID of the Media whose you want to purchase a license).</param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Function GetMediaComp(ByVal mediaId As Integer) As Image Implements IPartnerService.GetMediaComp
            Dim retVal As Image = Nothing
            Try
                retVal = ExecuteQuery(Of Image)("GetMediaComp",
                                                Function() MediaDataProxy.GetMediaComp(Me.Authentication, mediaId),
                                                Me.Authentication,
                                                mediaId)
            Catch ex As Exception
                ManageException(ex)
            End Try
            Return retVal
        End Function

        ''' <summary>
        ''' This method returns comp images in async mode.
        ''' Comp images can ONLY be used to evaluate the image as to suitability for a project, obtain client or internal company approvals, or experiment with layout alternatives.
        ''' </summary>
        ''' <param name="mediaId">Media ID (ID of the Media whose you want to purchase a license).</param>
        ''' <param name="userState">The user state object.</param>
        ''' <remarks></remarks>
        Public Sub GetMediaCompAsync(ByVal mediaId As Integer, ByVal userState As Object) Implements IPartnerService.GetMediaCompAsync
            Try
                Dim result = GetResultFromCache(Of Image)("GetMediaComp", Me.Authentication, mediaId)
                If result Is Nothing Then
                    MediaDataProxy.BeginGetMediaComp(Me.Authentication,
                                                     mediaId,
                                                     AddressOf GetMediaCompCallBack,
                                                     New Tuple(Of Integer, Object)(mediaId, userState))
                Else
                    OnGetMediaCompCompleted(New GetMediaCompCompletedEventArgs() With {.Error = Nothing,
                                                                                       .Result = True,
                                                                                       .MediaId = mediaId,
                                                                                       .Image = result,
                                                                                       .UserState = userState})
                End If
            Catch ex As Exception
                If TypeOf ex Is XmlRpcFaultException Then
                    Dim xmlrpcEx = CType(ex, XmlRpcFaultException)
                    OnGetMediaCompCompleted(New GetMediaCompCompletedEventArgs() With {.Error = Mapper.Map(Of XmlRpcFaultException, [Error])(xmlrpcEx),
                                                                                        .Result = False,
                                                                                        .UserState = userState,
                                                                                        .MediaId = mediaId})
                Else
                    Throw
                End If
            End Try
        End Sub

        Private Sub GetMediaCompCallBack(asr As IAsyncResult)
            Dim clientResult = CType(asr, XmlRpcAsyncResult)
            Dim proxy = CType(clientResult.ClientProtocol, IMediaData)
            Dim userTuple = CType(clientResult.AsyncState, Tuple(Of Integer, Object))
            Try
                Dim asyncResult = proxy.EndGetMediaComp(asr)
                Dim image = Mapper.Map(Of XmlRpcStruct, Image)(asyncResult)
                SetResultInCache(Of Image)("GetMediaComp", image, Me.Authentication, userTuple.Item1)
                OnGetMediaCompCompleted(New GetMediaCompCompletedEventArgs() With {.Error = Nothing,
                                                                                    .Result = True,
                                                                                    .Image = image,
                                                                                    .MediaId = userTuple.Item1,
                                                                                    .UserState = userTuple.Item2})
            Catch ex As Exception
                If TypeOf ex Is XmlRpcFaultException Then
                    Dim xmlrpcEx = CType(ex, XmlRpcFaultException)
                    OnGetMediaCompCompleted(New GetMediaCompCompletedEventArgs() With {.Error = Mapper.Map(Of XmlRpcFaultException, [Error])(xmlrpcEx),
                                                                                       .Result = False,
                                                                                       .MediaId = userTuple.Item1,
                                                                                       .UserState = userTuple.Item2})
                Else
                    Throw
                End If
            End Try
        End Sub

        ''' <summary>
        ''' Occurs when [get media comp completed].
        ''' </summary>
        ''' <remarks></remarks>
        Public Event GetMediaCompCompleted(ByVal sender As Object, ByVal e As GetMediaCompCompletedEventArgs) Implements IPartnerService.GetMediaCompCompleted

        Protected Sub OnGetMediaCompCompleted(e As GetMediaCompCompletedEventArgs)
            RaiseEvent GetMediaCompCompleted(Me, e)
        End Sub
#End Region

#Region "LoginUser"
        ''' <summary>
        ''' This method allows you to create an authenticated session to be able to use methods which need authentication.
        ''' If the user is autenticated, the method returns true, otherwise the method returns false.
        ''' The class that implements this interface must manage the user session and the session id.
        ''' </summary>
        ''' <param name="username">User Login.</param>
        ''' <param name="password">User Password.</param>
        ''' <returns>The session id if the user is autenticated, otherwise nothing.</returns>
        ''' <exception cref="FTTK.Exceptions.FotoliaException">The service throwns this exception if the login is failed.</exception>
        ''' <remarks></remarks>
        Public Function LoginUser(ByVal username As String, ByVal password As String) As String Implements IPartnerService.LoginUser
            Dim retVal As String = Nothing
            Try
                Dim response = Me.UserProxy.LoginUser(Me.Authentication, username, password)
                If response.ContainsKey("session_id") Then
                    Dim sessionId = response.Item("session_id").ToString()
                    If Not String.IsNullOrWhiteSpace(sessionId) Then
                        retVal = sessionId
                    End If
                End If
            Catch ex As Exception
                ManageException(ex)
            End Try
            Return retVal
        End Function

        ''' <summary>
        ''' This method allows you to create an authenticated session to be able to use methods which need authentication (in async mode).
        ''' The class that implements this interface must manage the user session and the session id.
        ''' </summary>
        ''' <param name="username">User Login.</param>
        ''' <param name="password">User Password.</param>
        ''' <param name="userState">The user state.</param>
        ''' <remarks></remarks>
        Public Sub LoginUserAsync(ByVal username As String, ByVal password As String, ByVal userState As Object) Implements IPartnerService.LoginUserAsync
            Try
                UserProxy.BeginLoginUser(Me.Authentication,
                                            username,
                                            password,
                                            AddressOf LoginUserCallBack,
                                            New Tuple(Of String, Object)(username, userState))
            Catch ex As Exception
                If TypeOf ex Is XmlRpcFaultException Then
                    Dim xmlrpcEx = CType(ex, XmlRpcFaultException)
                    OnLoginUserCompleted(New LoginUserCompletedEventArgs() With {.Error = Mapper.Map(Of XmlRpcFaultException, [Error])(xmlrpcEx),
                                                                                 .Result = False,
                                                                                 .UserState = userState,
                                                                                 .Username = username,
                                                                                 .SessionId = Nothing})
                Else
                    Throw
                End If
            End Try
        End Sub

        Private Sub LoginUserCallBack(asr As IAsyncResult)
            Dim clientResult = CType(asr, XmlRpcAsyncResult)
            Dim proxy = CType(clientResult.ClientProtocol, IUser)
            Dim userTuple = CType(clientResult.AsyncState, Tuple(Of String, Object))
            Try
                Dim sessionId As String = Nothing
                Dim asyncResult = proxy.EndLoginUser(asr)
                If asyncResult.ContainsKey("session_id") Then
                    sessionId = asyncResult.Item("session_id").ToString()
                End If
                OnLoginUserCompleted(New LoginUserCompletedEventArgs() With {.Error = Nothing,
                                                                            .Result = Not String.IsNullOrWhiteSpace(sessionId),
                                                                            .Username = userTuple.Item1,
                                                                            .UserState = userTuple.Item2,
                                                                            .SessionId = sessionId})
            Catch ex As Exception
                If TypeOf ex Is XmlRpcFaultException Then
                    Dim xmlrpcEx = CType(ex, XmlRpcFaultException)
                    OnLoginUserCompleted(New LoginUserCompletedEventArgs() With {.Error = Mapper.Map(Of XmlRpcFaultException, [Error])(xmlrpcEx),
                                                                                .Result = False,
                                                                                .Username = userTuple.Item1,
                                                                                .UserState = userTuple.Item2,
                                                                                 .SessionId = Nothing})
                Else
                    Throw
                End If
            End Try
        End Sub

        ''' <summary>
        ''' Occurs when [login user completed].
        ''' </summary>
        ''' <remarks></remarks>
        Public Event LoginUserCompleted(ByVal sender As Object, ByVal e As LoginUserCompletedEventArgs) Implements IPartnerService.LoginUserCompleted

        Protected Sub OnLoginUserCompleted(e As LoginUserCompletedEventArgs)
            RaiseEvent LoginUserCompleted(Me, e)
        End Sub
#End Region

#Region "LogoutUser"
        ''' <summary>
        ''' This method kills the authentified session. It is equivalent to logout from Fotolia website.
        ''' </summary>
        ''' <param name="sessionId">The session id.</param>
        ''' <returns>True if logout completed, false otherwise.</returns>
        ''' <remarks></remarks>
        Public Function LogoutUser(ByVal sessionId As String) As Boolean Implements IPartnerService.LogoutUser
            Dim retVal = False
            Try
                Dim response = Me.UserProxy.LogoutUser(Me.Authentication, sessionId)
                If response.ContainsKey("logout") Then
                    Dim result = response.Item("logout").ToString()
                    If String.Compare(result, "success", True) = 0 Then
                        retVal = True
                    End If
                End If
            Catch ex As Exception
                ManageException(ex)
            End Try
            Return retVal
        End Function

        ''' <summary>
        ''' This method kills the authentified session (in async mode). It is equivalent to logout from Fotolia website.
        ''' </summary>
        ''' <param name="sessionId">The session id.</param>
        ''' <param name="userState">State of the user.</param>
        ''' <remarks></remarks>
        Public Sub LogoutUserAsync(ByVal sessionId As String, ByVal userState As Object) Implements IPartnerService.LogoutUserAsync
            Try
                UserProxy.BeginLogoutUser(Me.Authentication,
                                            sessionId,
                                            AddressOf LogoutUserCallBack,
                                            New Tuple(Of String, Object)(sessionId, userState))
            Catch ex As Exception
                If TypeOf ex Is XmlRpcFaultException Then
                    Dim xmlrpcEx = CType(ex, XmlRpcFaultException)
                    OnLogoutUserCompleted(New LogoutUserCompletedEventArgs() With {.Error = Mapper.Map(Of XmlRpcFaultException, [Error])(xmlrpcEx),
                                                                                 .Result = False,
                                                                                 .UserState = userState,
                                                                                 .SessionId = sessionId})
                Else
                    Throw
                End If
            End Try
        End Sub

        Private Sub LogoutUserCallBack(asr As IAsyncResult)
            Dim clientResult = CType(asr, XmlRpcAsyncResult)
            Dim proxy = CType(clientResult.ClientProtocol, IUser)
            Dim userTuple = CType(clientResult.AsyncState, Tuple(Of String, Object))
            Try
                Dim result = False
                Dim asyncResult = proxy.EndLogoutUser(asr)
                If asyncResult.ContainsKey("logout") Then
                    Dim logoutResult = asyncResult.Item("logout").ToString()
                    If String.Compare(logoutResult, "success", True) = 0 Then
                        result = True
                    End If
                End If
                OnLogoutUserCompleted(New LogoutUserCompletedEventArgs() With {.Error = Nothing,
                                                                            .Result = result,
                                                                            .SessionId = userTuple.Item1,
                                                                            .UserState = userTuple.Item2})
            Catch ex As Exception
                If TypeOf ex Is XmlRpcFaultException Then
                    Dim xmlrpcEx = CType(ex, XmlRpcFaultException)
                    OnLogoutUserCompleted(New LogoutUserCompletedEventArgs() With {.Error = Mapper.Map(Of XmlRpcFaultException, [Error])(xmlrpcEx),
                                                                                .Result = False,
                                                                                .SessionId = userTuple.Item1,
                                                                                .UserState = userTuple.Item2})
                Else
                    Throw
                End If
            End Try
        End Sub

        ''' <summary>
        ''' Occurs when [logout user completed].
        ''' </summary>
        ''' <remarks></remarks>
        Public Event LogoutUserCompleted(ByVal sender As Object, ByVal e As LogoutUserCompletedEventArgs) Implements IPartnerService.LogoutUserCompleted


        Protected Sub OnLogoutUserCompleted(e As LogoutUserCompletedEventArgs)
            RaiseEvent LogoutUserCompleted(Me, e)
        End Sub
#End Region

#Region "GetUserData"
        ''' <summary>
        ''' This methods return data for logged user.
        ''' </summary>
        ''' <param name="sessionId">The user session id.</param>
        ''' <returns></returns>
        ''' <remarks>This method requires authentication with a valid session token.</remarks>
        Public Function GetUserData(ByVal sessionId As String) As UserData Implements IPartnerService.GetUserData
            Dim retVal As UserData = Nothing
            Try
                UserProxy.CookieContainer.Add(New Cookie("PHPSESSID", sessionId, "/", ".fotolia.com"))
                retVal = ExecuteQuery(Of UserData)("GetUserData",
                                                Function() UserProxy.GetUserData(Me.Authentication, sessionId),
                                                Me.Authentication,
                                                sessionId)
            Catch ex As Exception
                If TypeOf ex Is XmlRpcIllFormedXmlException Then
                    Throw New FotoliaException("Invalid Session Token", ex) With {.Code = "21"}
                Else
                    ManageException(ex)
                End If
            End Try
            Return retVal
        End Function

        ''' <summary>
        ''' This methods return data for logged user (in async mode).
        ''' </summary>
        ''' <param name="sessionId">The user session id.</param>
        ''' <param name="userState">The user state object.</param>
        ''' <remarks>This method requires authentication with a valid session token.</remarks>
        Public Sub GetUserDataAsync(ByVal sessionId As String, ByVal userState As Object) Implements IPartnerService.GetUserDataAsync
            Try
                Dim result = GetResultFromCache(Of UserData)("GetUserData", Me.Authentication, sessionId)
                If result Is Nothing Then
                    UserProxy.CookieContainer.Add(New Cookie("PHPSESSID", sessionId, "/", ".fotolia.com"))
                    UserProxy.BeginGetUserData(Me.Authentication,
                                                sessionId,
                                                AddressOf GetUserDataCallBack,
                                                New Tuple(Of String, Object)(sessionId, userState))
                Else
                    OnGetUserDataCompleted(New GetUserDataCompletedEventArgs() With {.Error = Nothing,
                                                                                    .Result = True,
                                                                                    .SessionId = sessionId,
                                                                                    .UserData = result,
                                                                                    .UserState = userState})
                End If
            Catch ex As Exception
                If TypeOf ex Is XmlRpcFaultException Then
                    Dim xmlrpcEx = CType(ex, XmlRpcFaultException)
                    OnGetUserDataCompleted(New GetUserDataCompletedEventArgs() With {.Error = Mapper.Map(Of XmlRpcFaultException, [Error])(xmlrpcEx),
                                                                                    .Result = False,
                                                                                    .UserState = userState,
                                                                                    .SessionId = sessionId})
                ElseIf TypeOf ex Is XmlRpcIllFormedXmlException Then
                    OnGetUserStatsCompleted(New GetUserStatsCompletedEventArgs() With {.Error = New FTTK.Error() With {.Code = "21",
                                                                                                                        .Message = "Invalid Session Token"},
                                                                                        .Result = False,
                                                                                        .UserState = userState,
                                                                                        .SessionId = sessionId})
                Else
                    Throw
                End If
            End Try
        End Sub

        Private Sub GetUserDataCallBack(asr As IAsyncResult)
            Dim clientResult = CType(asr, XmlRpcAsyncResult)
            Dim proxy = CType(clientResult.ClientProtocol, IUser)
            Dim userTuple = CType(clientResult.AsyncState, Tuple(Of String, Object))
            Try
                Dim asyncResult = proxy.EndGetUserData(asr)
                Dim data = Mapper.Map(Of XmlRpcStruct, UserData)(asyncResult)
                SetResultInCache(Of UserData)("GetUserData", data, Me.Authentication, userTuple.Item1)
                OnGetUserDataCompleted(New GetUserDataCompletedEventArgs() With {.Error = Nothing,
                                                                                .Result = True,
                                                                                .UserData = data,
                                                                                .SessionId = userTuple.Item1,
                                                                                .UserState = userTuple.Item2})
            Catch ex As Exception
                If TypeOf ex Is XmlRpcFaultException Then
                    Dim xmlrpcEx = CType(ex, XmlRpcFaultException)
                    OnGetUserDataCompleted(New GetUserDataCompletedEventArgs() With {.Error = Mapper.Map(Of XmlRpcFaultException, [Error])(xmlrpcEx),
                                                                                    .Result = False,
                                                                                    .SessionId = userTuple.Item1,
                                                                                    .UserState = userTuple.Item2})
                ElseIf TypeOf ex Is XmlRpcIllFormedXmlException Then
                    OnGetUserStatsCompleted(New GetUserStatsCompletedEventArgs() With {.Error = New FTTK.Error() With {.Code = "21",
                                                                                                                        .Message = "Invalid Session Token"},
                                                                                        .Result = False,
                                                                                        .UserState = userTuple.Item2,
                                                                                        .SessionId = userTuple.Item1})
                Else
                    Throw
                End If
            End Try
        End Sub

        Public Event GetUserDataCompleted(ByVal sender As Object, ByVal e As GetUserDataCompletedEventArgs) Implements IPartnerService.GetUserDataCompleted

        Protected Sub OnGetUserDataCompleted(e As GetUserDataCompletedEventArgs)
            RaiseEvent GetUserDataCompleted(Me, e)
        End Sub
#End Region

#Region "GetUserStats"
        ''' <summary>
        ''' This methods returns statistics for logged user. 
        ''' </summary>
        ''' <param name="sessionId">The user session id.</param>
        ''' <returns></returns>
        ''' <remarks>This method requires authentication with a valid session token.</remarks>
        Public Function GetUserStats(ByVal sessionId As String) As UserStats Implements IPartnerService.GetUserStats
            Dim retVal As UserStats = Nothing
            Try
                UserProxy.CookieContainer.Add(New Cookie("PHPSESSID", sessionId, "/", ".fotolia.com"))
                retVal = ExecuteQuery(Of UserStats)("GetUserStats",
                                                    Function() UserProxy.GetUserStats(Me.Authentication, sessionId),
                                                    Me.Authentication,
                                                    sessionId)
            Catch ex As Exception
                If TypeOf ex Is XmlRpcIllFormedXmlException Then
                    Throw New FotoliaException("Invalid Session Token", ex) With {.Code = "21"}
                Else
                    ManageException(ex)
                End If
            End Try
            Return retVal
        End Function

        ''' <summary>
        ''' This methods returns statistics for logged user. 
        ''' </summary>
        ''' <param name="sessionId">The user session id.</param>
        ''' <param name="userState">The user state object.</param>
        ''' <remarks>This method requires authentication with a valid session token.</remarks>
        Public Sub GetUserStatsAsync(ByVal sessionId As String, ByVal userState As Object) Implements IPartnerService.GetUserStatsAsync
            Try
                Dim result = GetResultFromCache(Of UserStats)("GetUserStats", Me.Authentication, sessionId)
                If result Is Nothing Then
                    UserProxy.CookieContainer.Add(New Cookie("PHPSESSID", sessionId, "/", ".fotolia.com"))
                    UserProxy.BeginGetUserStats(Me.Authentication,
                                                sessionId,
                                                AddressOf GetUserStatsCallBack,
                                                New Tuple(Of String, Object)(sessionId, userState))
                Else
                    OnGetUserStatsCompleted(New GetUserStatsCompletedEventArgs() With {.Error = Nothing,
                                                                                       .Result = True,
                                                                                       .SessionId = sessionId,
                                                                                       .UserStats = result,
                                                                                       .UserState = userState})
                End If
            Catch ex As Exception
                If TypeOf ex Is XmlRpcFaultException Then
                    Dim xmlrpcEx = CType(ex, XmlRpcFaultException)
                    OnGetUserStatsCompleted(New GetUserStatsCompletedEventArgs() With {.Error = Mapper.Map(Of XmlRpcFaultException, [Error])(xmlrpcEx),
                                                                                        .Result = False,
                                                                                        .UserState = userState,
                                                                                        .SessionId = sessionId})
                ElseIf TypeOf ex Is XmlRpcIllFormedXmlException Then
                    OnGetUserStatsCompleted(New GetUserStatsCompletedEventArgs() With {.Error = New FTTK.Error() With {.Code = "21",
                                                                                                                        .Message = "Invalid Session Token"},
                                                                                        .Result = False,
                                                                                        .UserState = userState,
                                                                                        .SessionId = sessionId})
                Else
                    Throw
                End If
            End Try
        End Sub

        Private Sub GetUserStatsCallBack(asr As IAsyncResult)
            Dim clientResult = CType(asr, XmlRpcAsyncResult)
            Dim proxy = CType(clientResult.ClientProtocol, IUser)
            Dim userTuple = CType(clientResult.AsyncState, Tuple(Of String, Object))
            Try
                Dim asyncResult = proxy.EndGetUserStats(asr)
                Dim data = Mapper.Map(Of XmlRpcStruct, UserStats)(asyncResult)
                SetResultInCache(Of UserStats)("GetUserStats", data, Me.Authentication, userTuple.Item1)
                OnGetUserStatsCompleted(New GetUserStatsCompletedEventArgs() With {.Error = Nothing,
                                                                                .Result = True,
                                                                                .UserStats = data,
                                                                                .SessionId = userTuple.Item1,
                                                                                .UserState = userTuple.Item2})
            Catch ex As Exception
                If TypeOf ex Is XmlRpcFaultException Then
                    Dim xmlrpcEx = CType(ex, XmlRpcFaultException)
                    OnGetUserStatsCompleted(New GetUserStatsCompletedEventArgs() With {.Error = Mapper.Map(Of XmlRpcFaultException, [Error])(xmlrpcEx),
                                                                                    .Result = False,
                                                                                    .SessionId = userTuple.Item1,
                                                                                    .UserState = userTuple.Item2})
                ElseIf TypeOf ex Is XmlRpcIllFormedXmlException Then
                    OnGetUserStatsCompleted(New GetUserStatsCompletedEventArgs() With {.Error = New FTTK.Error() With {.Code = "21",
                                                                                                                        .Message = "Invalid Session Token"},
                                                                                        .Result = False,
                                                                                        .UserState = userTuple.Item2,
                                                                                        .SessionId = userTuple.Item1})
                Else
                    Throw
                End If
            End Try
        End Sub

        ''' <summary>
        ''' Occurs when [get user stats completed].
        ''' </summary>
        ''' <remarks></remarks>
        Public Event GetUserStatsCompleted(ByVal sender As Object, ByVal e As GetUserStatsCompletedEventArgs) Implements IPartnerService.GetUserStatsCompleted

        Protected Sub OnGetUserStatsCompleted(e As GetUserStatsCompletedEventArgs)
            RaiseEvent GetUserStatsCompleted(Me, e)
        End Sub
#End Region

#Region "GetUserGalleries"
        ''' <summary>
        ''' This methods return private galleries for logged user. 
        ''' </summary>
        ''' <param name="sessionId">The user session id.</param>
        ''' <returns></returns>
        ''' <remarks>This method requires authentication with a valid session token.</remarks>
        Public Function GetUserGalleries(ByVal sessionId As String) As IEnumerable(Of Gallery) Implements IPartnerService.GetUserGalleries
            Dim retVal As IEnumerable(Of Gallery) = Nothing
            Try
                UserProxy.CookieContainer.Add(New Cookie("PHPSESSID", sessionId, "/", ".fotolia.com"))
                retVal = ExecuteQuery(Of IEnumerable(Of Gallery))("GetUserGalleries",
                                                                  Function() UserProxy.GetUserGalleries(Me.Authentication, sessionId),
                                                                  Me.Authentication,
                                                                  sessionId)
            Catch ex As Exception
                If TypeOf ex Is XmlRpcIllFormedXmlException Then
                    Throw New FotoliaException("Invalid Session Token", ex) With {.Code = "21"}
                Else
                    ManageException(ex)
                End If
            End Try
            Return retVal
        End Function

        ''' <summary>
        ''' This methods return private galleries for logged user in async mode.
        ''' </summary>
        ''' <param name="sessionId">The user session id.</param>
        ''' <param name="userState">The user state object.</param>
        ''' <remarks>This method requires authentication with a valid session token.</remarks>
        Public Sub GetUserGalleriesAsync(ByVal sessionId As String, ByVal userState As Object) Implements IPartnerService.GetUserGalleriesAsync
            Try
                Dim result = GetResultFromCache(Of IEnumerable(Of Gallery))("GetUserGalleries", Me.Authentication, sessionId)
                If result Is Nothing Then
                    UserProxy.CookieContainer.Add(New Cookie("PHPSESSID", sessionId, "/", ".fotolia.com"))
                    UserProxy.BeginGetUserGalleries(Me.Authentication,
                                                    sessionId,
                                                    AddressOf GetUserGalleriesCallBack,
                                                    New Tuple(Of String, Object)(sessionId, userState))
                Else
                    OnGetUserGalleriesCompleted(New GetUserGalleriesCompletedEventArgs() With {.Error = Nothing,
                                                                                       .Result = True,
                                                                                       .SessionId = sessionId,
                                                                                       .Galleries = result,
                                                                                       .UserState = userState})
                End If
            Catch ex As Exception
                If TypeOf ex Is XmlRpcFaultException Then
                    Dim xmlrpcEx = CType(ex, XmlRpcFaultException)
                    OnGetUserGalleriesCompleted(New GetUserGalleriesCompletedEventArgs() With {.Error = Mapper.Map(Of XmlRpcFaultException, [Error])(xmlrpcEx),
                                                                                        .Result = False,
                                                                                        .UserState = userState,
                                                                                        .SessionId = sessionId})
                ElseIf TypeOf ex Is XmlRpcIllFormedXmlException Then
                    OnGetUserGalleriesCompleted(New GetUserGalleriesCompletedEventArgs() With {.Error = New FTTK.Error() With {.Code = "21",
                                                                                                                        .Message = "Invalid Session Token"},
                                                                                        .Result = False,
                                                                                        .UserState = userState,
                                                                                        .SessionId = sessionId})
                Else
                    Throw
                End If
            End Try
        End Sub

        Private Sub GetUserGalleriesCallBack(asr As IAsyncResult)
            Dim clientResult = CType(asr, XmlRpcAsyncResult)
            Dim proxy = CType(clientResult.ClientProtocol, IUser)
            Dim userTuple = CType(clientResult.AsyncState, Tuple(Of String, Object))
            Try
                Dim asyncResult = proxy.EndGetUserGalleries(asr)
                Dim data = Mapper.Map(Of XmlRpcStruct(), IEnumerable(Of Gallery))(asyncResult)
                SetResultInCache(Of IEnumerable(Of Gallery))("GetUserGalleries", data, Me.Authentication, userTuple.Item1)
                OnGetUserGalleriesCompleted(New GetUserGalleriesCompletedEventArgs() With {.Error = Nothing,
                                                                                .Result = True,
                                                                                .Galleries = data,
                                                                                .SessionId = userTuple.Item1,
                                                                                .UserState = userTuple.Item2})
            Catch ex As Exception
                If TypeOf ex Is XmlRpcFaultException Then
                    Dim xmlrpcEx = CType(ex, XmlRpcFaultException)
                    OnGetUserGalleriesCompleted(New GetUserGalleriesCompletedEventArgs() With {.Error = Mapper.Map(Of XmlRpcFaultException, [Error])(xmlrpcEx),
                                                                                    .Result = False,
                                                                                    .SessionId = userTuple.Item1,
                                                                                    .UserState = userTuple.Item2})
                ElseIf TypeOf ex Is XmlRpcIllFormedXmlException Then
                    OnGetUserGalleriesCompleted(New GetUserGalleriesCompletedEventArgs() With {.Error = New FTTK.Error() With {.Code = "21",
                                                                                                                        .Message = "Invalid Session Token"},
                                                                                        .Result = False,
                                                                                        .UserState = userTuple.Item2,
                                                                                        .SessionId = userTuple.Item1})
                Else
                    Throw
                End If
            End Try
        End Sub

        ''' <summary>
        ''' Occurs when [get user galleries completed].
        ''' </summary>
        ''' <remarks></remarks>
        Public Event GetUserGalleriesCompleted(ByVal sender As Object, ByVal e As GetUserGalleriesCompletedEventArgs) Implements IPartnerService.GetUserGalleriesCompleted

        Protected Sub OnGetUserGalleriesCompleted(e As GetUserGalleriesCompletedEventArgs)
            RaiseEvent GetUserGalleriesCompleted(Me, e)
        End Sub
#End Region

#Region "GetUserGalleryMedias"

        ''' <summary>
        ''' This methods allows to search media in logged user galleries or lightbox. 
        ''' </summary>
        ''' <param name="sessionId">The user session id.</param>
        ''' <param name="galleryId">The gallery id. If not id sent, retrieve the content of the logged user Lightbox.</param>
        ''' <param name="numberOfResults">The total number of results.</param>
        ''' <param name="pageNumber">Page number to display.</param>
        ''' <param name="mediaPerPage">Maximum number of media returned. Valid values: 1 to 64.</param>
        ''' <param name="thumbnailSize">Size of the thumbnail.</param>
        ''' <param name="detailLevel">The detail level.</param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Function GetUserGalleryMedias(ByVal sessionId As String,
                                             ByVal galleryId As String,
                                             ByRef numberOfResults As Integer,
                                             Optional pageNumber As Integer = 1,
                                             Optional mediaPerPage As Integer = 32,
                                             Optional thumbnailSize As Entities.SearchThumbnailSize = Entities.SearchThumbnailSize.Size110,
                                             Optional detailLevel As SearchDetailLevel = SearchDetailLevel.Base) As IEnumerable(Of Media) Implements IPartnerService.GetUserGalleryMedias
            Dim retVal As IEnumerable(Of Media) = Nothing
            Try
                Dim cacheValue = GetResultFromCache(Of Tuple(Of IEnumerable(Of Media), Integer))("GetUserGalleryMedias", Me.Authentication,
                                                                                                sessionId, galleryId, pageNumber, mediaPerPage,
                                                                                                thumbnailSize, detailLevel)
                If cacheValue IsNot Nothing Then
                    retVal = cacheValue.Item1
                    numberOfResults = cacheValue.Item2
                End If
                If retVal Is Nothing Then
                    UserProxy.CookieContainer.Add(New Cookie("PHPSESSID", sessionId, "/", ".fotolia.com"))
                    Dim result = UserProxy.GetUserGalleryMedias(Me.Authentication, sessionId, pageNumber, mediaPerPage,
                                                                FTTK.XmlRpc.SearchThumbnailSize.FromEntitySize(thumbnailSize),
                                                                If(galleryId Is Nothing, String.Empty, galleryId),
                                                                If(detailLevel = SearchDetailLevel.Base, 0, 1))
                    numberOfResults = result.GetValueOrDefault(Of Integer)("nb_results", -1)
                    retVal = Mapper.Map(Of XmlRpcStruct(), IEnumerable(Of Media))(result.Values.OfType(Of XmlRpcStruct).ToArray())
                    SetResultInCache(Of Tuple(Of IEnumerable(Of Media), Integer))("GetUserGalleryMedias", New Tuple(Of IEnumerable(Of Media), Integer)(retVal, numberOfResults),
                                                                                  Me.Authentication, sessionId, galleryId, pageNumber, mediaPerPage, thumbnailSize, detailLevel)
                End If
            Catch ex As Exception
                If TypeOf ex Is XmlRpcIllFormedXmlException Then
                    Throw New FotoliaException("Invalid Session Token", ex) With {.Code = "21"}
                Else
                    ManageException(ex)
                End If
            End Try
            Return retVal
        End Function

        ''' <summary>
        ''' This methods allows to search media in logged user galleries or lightbox.
        ''' </summary>
        ''' <param name="sessionId">The user session id.</param>
        ''' <param name="galleryId">The gallery id. If not id sent, retrieve the content of the logged user Lightbox.</param>
        ''' <param name="userState">The object state user..</param>
        ''' <param name="pageNumber">Page number to display.</param>
        ''' <param name="mediaPerPage">Maximum number of media returned. Valid values: 1 to 64.</param>
        ''' <param name="thumbnailSize">Size of the thumbnail.</param>
        ''' <param name="detailLevel">The detail level.</param>
        ''' <remarks></remarks>
        Public Sub GetUserGalleryMediasAsync(ByVal sessionId As String,
                                             ByVal galleryId As String,
                                             ByVal userState As Object,
                                             Optional pageNumber As Integer = 1,
                                             Optional mediaPerPage As Integer = 32,
                                             Optional thumbnailSize As Entities.SearchThumbnailSize = Entities.SearchThumbnailSize.Size110,
                                             Optional detailLevel As SearchDetailLevel = SearchDetailLevel.Base) Implements IPartnerService.GetUserGalleryMediasAsync
            Try
                Dim result = GetResultFromCache(Of IEnumerable(Of Media))("GetUserGalleryMedias", Me.Authentication,
                                                                        sessionId, galleryId, pageNumber, mediaPerPage,
                                                                        thumbnailSize, detailLevel)
                If result Is Nothing Then
                    UserProxy.CookieContainer.Add(New Cookie("PHPSESSID", sessionId, "/", ".fotolia.com"))
                    UserProxy.BeginGetUserGalleryMedias(Me.Authentication, sessionId, pageNumber, pageNumber, thumbnailSize, galleryId, detailLevel,
                                                    AddressOf GetUserGalleryMediasCallBack,
                                                    New Tuple(Of String, String, Integer, Integer, Entities.SearchThumbnailSize, Entities.SearchDetailLevel, Object)(sessionId, galleryId, pageNumber,
                                                                                                           mediaPerPage, thumbnailSize, detailLevel, userState))
                Else
                    OnGetUserGalleryMediasCompleted(New GetUserGalleryMediasCompletedEventArgs() With {.Error = Nothing, .Result = True, .SessionId = sessionId,
                                                                                                       .MediaList = result, .MediaPerPage = mediaPerPage,
                                                                                                       .PageNumber = pageNumber, .UserState = userState})
                End If
            Catch ex As Exception
                If TypeOf ex Is XmlRpcFaultException Then
                    Dim xmlrpcEx = CType(ex, XmlRpcFaultException)
                    OnGetUserGalleryMediasCompleted(New GetUserGalleryMediasCompletedEventArgs() With {.Error = Mapper.Map(Of XmlRpcFaultException, [Error])(xmlrpcEx),
                                                                                                        .Result = False, .UserState = userState, .SessionId = sessionId,
                                                                                                       .MediaPerPage = mediaPerPage, .PageNumber = pageNumber})
                ElseIf TypeOf ex Is XmlRpcIllFormedXmlException Then
                    OnGetUserGalleryMediasCompleted(New GetUserGalleryMediasCompletedEventArgs() With {.Error = New FTTK.Error() With {.Code = "21",
                                                                                                                                       .Message = "Invalid Session Token"},
                                                                                                        .Result = False, .UserState = userState, .SessionId = sessionId,
                                                                                                       .MediaPerPage = mediaPerPage, .PageNumber = pageNumber})
                Else
                    Throw
                End If
            End Try
        End Sub

        Private Sub GetUserGalleryMediasCallBack(asr As IAsyncResult)
            Dim clientResult = CType(asr, XmlRpcAsyncResult)
            Dim proxy = CType(clientResult.ClientProtocol, IUser)
            Dim userTuple = CType(clientResult.AsyncState, Tuple(Of String, String, Integer, Integer, Entities.SearchThumbnailSize, Entities.SearchDetailLevel, Object))
            Try
                Dim asyncResult = proxy.EndGetUserGalleryMedias(asr)
                'Dim numberOfResults = asyncResult.GetValueOrDefault(Of Integer)("nb_results", -1)
                'Dim data = Mapper.Map(Of XmlRpcStruct(), IEnumerable(Of Media))(asyncResult.Values.OfType(Of XmlRpcStruct).ToArray())

                'SetResultInCache(Of Tuple(Of IEnumerable(Of Media), Integer))("GetUserGalleryMedias", New Tuple(Of IEnumerable(Of Media), Integer)(data, numberOfResults),
                '                                                            Me.Authentication, userTuple.Item1, userTuple.Item2,
                '                                                            userTuple.Item3, userTuple.Item4, userTuple.Item5, userTuple.Item6)

                OnGetUserGalleryMediasCompleted(New GetUserGalleryMediasCompletedEventArgs() With {.Error = Nothing, .Result = True, .MediaList = Nothing,
                                                                                                   .SessionId = userTuple.Item1, .PageNumber = userTuple.Item3,
                                                                                                   .MediaPerPage = userTuple.Item4, .UserState = userTuple.Item7})
            Catch ex As Exception
                If TypeOf ex Is XmlRpcFaultException Then
                    Dim xmlrpcEx = CType(ex, XmlRpcFaultException)
                    OnGetUserGalleryMediasCompleted(New GetUserGalleryMediasCompletedEventArgs() With {.Error = Mapper.Map(Of XmlRpcFaultException, [Error])(xmlrpcEx),
                                                                                                       .Result = False, .SessionId = userTuple.Item1,
                                                                                                       .PageNumber = userTuple.Item3, .MediaPerPage = userTuple.Item4,
                                                                                                       .UserState = userTuple.Item7})
                ElseIf TypeOf ex Is XmlRpcIllFormedXmlException Then
                    OnGetUserGalleryMediasCompleted(New GetUserGalleryMediasCompletedEventArgs() With {.Error = New FTTK.Error() With {.Code = "21",
                                                                                                                                       .Message = "Invalid Session Token"},
                                                                                                       .Result = False, .SessionId = userTuple.Item1,
                                                                                                       .PageNumber = userTuple.Item3, .MediaPerPage = userTuple.Item4,
                                                                                                       .UserState = userTuple.Item7})
                Else
                    Throw
                End If
            End Try
        End Sub

        ''' <summary>
        ''' Occurs when [get user gallery medias completed].
        ''' </summary>
        ''' <remarks></remarks>
        Public Event GetUserGalleryMediasCompleted(ByVal sender As Object, ByVal e As GetUserGalleryMediasCompletedEventArgs) Implements IPartnerService.GetUserGalleryMediasCompleted

        Protected Sub OnGetUserGalleryMediasCompleted(e As GetUserGalleryMediasCompletedEventArgs)
            RaiseEvent GetUserGalleryMediasCompleted(Me, e)
        End Sub
#End Region

#Region "CreateUserGallery"
        ''' <summary>
        ''' Creates a new user gallery.
        ''' </summary>
        ''' <param name="sessionId">The session id.</param>
        ''' <param name="galleryName">Name of the gallery.</param>
        ''' <returns>The method returns the gallery id or nothing if gallery isn't created.</returns>
        ''' <remarks></remarks>
        Public Function CreateUserGallery(ByVal sessionId As String, ByVal galleryName As String) As String Implements IPartnerService.CreateUserGallery
            Dim retVal As String = Nothing
            Try
                UserProxy.CookieContainer.Add(New Cookie("PHPSESSID", sessionId, "/", ".fotolia.com"))
                Dim response = Me.UserProxy.CreateUserGallery(Me.Authentication, sessionId, galleryName)
                If response.ContainsKey("id") Then
                    Dim galleryid = response.Item("id").ToString()
                    If Not String.IsNullOrWhiteSpace(galleryid) Then
                        retVal = galleryid
                    End If
                End If
            Catch ex As Exception
                If TypeOf ex Is XmlRpcIllFormedXmlException Then
                    Throw New FotoliaException("Invalid Session Token", ex) With {.Code = "21"}
                Else
                    ManageException(ex)
                End If
            End Try
            Return retVal
        End Function

        ''' <summary>
        ''' Creates the user gallery async.
        ''' </summary>
        ''' <param name="sessionId">The session id.</param>
        ''' <param name="galleryName">Name of the gallery.</param>
        ''' <param name="userState">The user state object.</param>
        ''' <remarks></remarks>
        Public Sub CreateUserGalleryAsync(ByVal sessionId As String, ByVal galleryName As String, ByVal userState As Object) Implements IPartnerService.CreateUserGalleryAsync
            Try
                UserProxy.CookieContainer.Add(New Cookie("PHPSESSID", sessionId, "/", ".fotolia.com"))
                UserProxy.BeginCreateUserGallery(Me.Authentication, sessionId, galleryName,
                                                AddressOf CreateUserGalleryCallBack,
                                                New Tuple(Of String, String, Object)(sessionId, galleryName, userState))
            Catch ex As Exception
                If TypeOf ex Is XmlRpcFaultException Then
                    Dim xmlrpcEx = CType(ex, XmlRpcFaultException)
                    OnCreateUserGalleryCompleted(New CreateUserGalleryCompletedEventArgs() With {.Error = Mapper.Map(Of XmlRpcFaultException, [Error])(xmlrpcEx),
                                                                                                 .Result = False,
                                                                                                 .UserState = userState,
                                                                                                 .GalleryName = galleryName,
                                                                                                 .SessionId = sessionId})
                Else
                    Throw
                End If
            End Try
        End Sub

        Private Sub CreateUserGalleryCallBack(asr As IAsyncResult)
            Dim clientResult = CType(asr, XmlRpcAsyncResult)
            Dim proxy = CType(clientResult.ClientProtocol, IUser)
            Dim userTuple = CType(clientResult.AsyncState, Tuple(Of String, String, Object))
            Try
                Dim galleryId As String = Nothing
                Dim asyncResult = proxy.EndCreateUserGallery(asr)
                If asyncResult.ContainsKey("id") Then
                    galleryId = asyncResult.Item("id").ToString()
                End If
                OnCreateUserGalleryCompleted(New CreateUserGalleryCompletedEventArgs() With {.Error = Nothing,
                                                                                            .Result = Not String.IsNullOrWhiteSpace(galleryId),
                                                                                            .GalleryName = userTuple.Item2,
                                                                                            .UserState = userTuple.Item3,
                                                                                            .SessionId = userTuple.Item1,
                                                                                            .GalleryId = galleryId})
            Catch ex As Exception
                If TypeOf ex Is XmlRpcFaultException Then
                    Dim xmlrpcEx = CType(ex, XmlRpcFaultException)
                    OnCreateUserGalleryCompleted(New CreateUserGalleryCompletedEventArgs() With {.Error = Mapper.Map(Of XmlRpcFaultException, [Error])(xmlrpcEx),
                                                                                                .Result = False,
                                                                                                .GalleryName = userTuple.Item2,
                                                                                                .UserState = userTuple.Item3,
                                                                                                .SessionId = userTuple.Item1})
                Else
                    Throw
                End If
            End Try
        End Sub

        Public Event CreateUserGalleryCompleted(ByVal sender As Object, ByVal e As CreateUserGalleryCompletedEventArgs) Implements IPartnerService.CreateUserGalleryCompleted

        Protected Sub OnCreateUserGalleryCompleted(e As CreateUserGalleryCompletedEventArgs)
            RaiseEvent CreateUserGalleryCompleted(Me, e)
        End Sub
#End Region

#Region "DeleteUserGallery"
        ''' <summary>
        ''' Deletes the user gallery.
        ''' </summary>
        ''' <param name="sessionId">The session id.</param>
        ''' <param name="galleryId">Id of the gallery to delete.</param>
        ''' <returns>TRUE if the gallery is deleted, otherwise FALSE.</returns>
        ''' <remarks></remarks>
        Public Function DeleteUserGallery(ByVal sessionId As String, ByVal galleryId As String) As Boolean Implements IPartnerService.DeleteUserGallery
            Dim retVal As Boolean = False
            Try
                UserProxy.CookieContainer.Add(New Cookie("PHPSESSID", sessionId, "/", ".fotolia.com"))
                Dim response = Me.UserProxy.DeleteUserGallery(Me.Authentication, sessionId, galleryId)
                If response.ContainsKey("deleteUserGallery") Then
                    Dim result = response.Item("deleteUserGallery").ToString()
                    If String.Compare(result, "SUCCESS", True) = 0 Then
                        retVal = True
                    End If
                End If
            Catch ex As Exception
                If TypeOf ex Is XmlRpcIllFormedXmlException Then
                    Throw New FotoliaException("Invalid Session Token", ex) With {.Code = "21"}
                Else
                    ManageException(ex)
                End If
            End Try
            Return retVal
        End Function

        ''' <summary>
        ''' Deletes the user gallery async.
        ''' </summary>
        ''' <param name="sessionId">The session id.</param>
        ''' <param name="galleryId">Id of the gallery to delete.</param>
        ''' <param name="userState">The user state object.</param>
        ''' <remarks></remarks>
        Public Sub DeleteUserGalleryAsync(ByVal sessionId As String, ByVal galleryId As String, ByVal userState As Object) Implements IPartnerService.DeleteUserGalleryAsync
            Try
                UserProxy.CookieContainer.Add(New Cookie("PHPSESSID", sessionId, "/", ".fotolia.com"))
                UserProxy.BeginDeleteUserGallery(Me.Authentication, sessionId, galleryId,
                                                AddressOf DeleteUserGalleryCallBack,
                                                New Tuple(Of String, String, Object)(sessionId, galleryId, userState))
            Catch ex As Exception
                If TypeOf ex Is XmlRpcFaultException Then
                    Dim xmlrpcEx = CType(ex, XmlRpcFaultException)
                    OnDeleteUserGalleryCompleted(New DeleteUserGalleryCompletedEventArgs() With {.Error = Mapper.Map(Of XmlRpcFaultException, [Error])(xmlrpcEx),
                                                                                                 .Result = False,
                                                                                                 .UserState = userState,
                                                                                                 .GalleryId = galleryId,
                                                                                                 .SessionId = sessionId})
                Else
                    Throw
                End If
            End Try
        End Sub

        Private Sub DeleteUserGalleryCallBack(asr As IAsyncResult)
            Dim clientResult = CType(asr, XmlRpcAsyncResult)
            Dim proxy = CType(clientResult.ClientProtocol, IUser)
            Dim userTuple = CType(clientResult.AsyncState, Tuple(Of String, String, Object))
            Try
                Dim retval = False
                Dim asyncResult = proxy.EndDeleteUserGallery(asr)
                If asyncResult.ContainsKey("deleteUserGallery") Then
                    Dim result = asyncResult.Item("deleteUserGallery").ToString()
                    If String.Compare(result, "SUCCESS", True) = 0 Then
                        retval = True
                    End If
                End If
                OnDeleteUserGalleryCompleted(New DeleteUserGalleryCompletedEventArgs() With {.Error = Nothing,
                                                                                            .Result = retval,
                                                                                            .UserState = userTuple.Item3,
                                                                                            .SessionId = userTuple.Item1,
                                                                                            .GalleryId = userTuple.Item2})
            Catch ex As Exception
                If TypeOf ex Is XmlRpcFaultException Then
                    Dim xmlrpcEx = CType(ex, XmlRpcFaultException)
                    OnDeleteUserGalleryCompleted(New DeleteUserGalleryCompletedEventArgs() With {.Error = Mapper.Map(Of XmlRpcFaultException, [Error])(xmlrpcEx),
                                                                                                .Result = False,
                                                                                                .GalleryId = userTuple.Item2,
                                                                                                .UserState = userTuple.Item3,
                                                                                                .SessionId = userTuple.Item1})
                Else
                    Throw
                End If
            End Try
        End Sub

        Public Event DeleteUserGalleryCompleted(ByVal sender As Object, ByVal e As DeleteUserGalleryCompletedEventArgs) Implements IPartnerService.DeleteUserGalleryCompleted

        Protected Sub OnDeleteUserGalleryCompleted(e As DeleteUserGalleryCompletedEventArgs)
            RaiseEvent DeleteUserGalleryCompleted(Me, e)
        End Sub
#End Region

#Region "AddToUserGallery"
        ''' <summary>
        ''' This methods allows you to add a content to your default lightbox or any of your existing galleries.
        ''' </summary>
        ''' <param name="sessionId">The session id.</param>
        ''' <param name="mediaId">The media id.</param>
        ''' <param name="galleryId">The gallery id.</param>
        ''' <returns><c>true</c> if media is added correctly, otherwise <c>false.</c></returns>
        ''' <remarks></remarks>
        Public Function AddToUserGallery(ByVal sessionId As String, ByVal mediaId As Integer, ByVal galleryId As String) As Boolean Implements IPartnerService.AddToUserGallery
            Dim retVal As Boolean = False
            Try
                UserProxy.CookieContainer.Add(New Cookie("PHPSESSID", sessionId, "/", ".fotolia.com"))
                Dim response = Me.UserProxy.AddToUserGallery(Me.Authentication, sessionId, mediaId, If(galleryId Is Nothing, String.Empty, galleryId))
                If response.ContainsKey("addtousergallery") Then
                    Dim result = response.Item("addtousergallery").ToString()
                    If String.Compare(result, "SUCCESS", True) = 0 Then
                        retVal = True
                    End If
                End If
            Catch ex As Exception
                If TypeOf ex Is XmlRpcIllFormedXmlException Then
                    Throw New FotoliaException("Invalid Session Token", ex) With {.Code = "21"}
                Else
                    ManageException(ex)
                End If
            End Try
            Return retVal
        End Function

        ''' <summary>
        ''' This methods allows you to add a content to your default lightbox or any of your existing galleries.
        ''' </summary>
        ''' <param name="sessionId">The session id.</param>
        ''' <param name="mediaId">The media id.</param>
        ''' <param name="galleryId">The gallery id.</param>
        ''' <param name="userState">The user state object.</param>
        ''' <remarks></remarks>
        Public Sub AddToUserGalleryAsync(ByVal sessionId As String, ByVal mediaId As Integer, ByVal galleryId As String, ByVal userState As Object) Implements IPartnerService.AddToUserGalleryAsync
            Try
                UserProxy.CookieContainer.Add(New Cookie("PHPSESSID", sessionId, "/", ".fotolia.com"))
                UserProxy.BeginAddToUserGallery(Me.Authentication, sessionId, mediaId, If(galleryId Is Nothing, String.Empty, galleryId),
                                                AddressOf AddToUserGalleryCallBack,
                                                New Tuple(Of String, Integer, String, Object)(sessionId, mediaId, galleryId, userState))
            Catch ex As Exception
                If TypeOf ex Is XmlRpcFaultException Then
                    Dim xmlrpcEx = CType(ex, XmlRpcFaultException)
                    OnAddToUserGalleryCompleted(New AddToUserGalleryCompletedEventArgs() With {.Error = Mapper.Map(Of XmlRpcFaultException, [Error])(xmlrpcEx),
                                                                                               .Result = False,
                                                                                               .UserState = userState,
                                                                                               .GalleryId = galleryId,
                                                                                               .SessionId = sessionId,
                                                                                               .MediaId = mediaId})
                Else
                    Throw
                End If
            End Try
        End Sub

        Private Sub AddToUserGalleryCallBack(asr As IAsyncResult)
            Dim clientResult = CType(asr, XmlRpcAsyncResult)
            Dim proxy = CType(clientResult.ClientProtocol, IUser)
            Dim userTuple = CType(clientResult.AsyncState, Tuple(Of String, Integer, String, Object))
            Try
                Dim retval = False
                Dim asyncResult = proxy.EndAddToUserGallery(asr)
                If asyncResult.ContainsKey("addtousergallery") Then
                    Dim result = asyncResult.Item("addtousergallery").ToString()
                    If String.Compare(result, "SUCCESS", True) = 0 Then
                        retval = True
                    End If
                End If
                OnAddToUserGalleryCompleted(New AddToUserGalleryCompletedEventArgs() With {.Error = Nothing,
                                                                                           .Result = retval,
                                                                                           .UserState = userTuple.Item4,
                                                                                           .SessionId = userTuple.Item1,
                                                                                           .GalleryId = userTuple.Item3,
                                                                                           .MediaId = userTuple.Item2})
            Catch ex As Exception
                If TypeOf ex Is XmlRpcFaultException Then
                    Dim xmlrpcEx = CType(ex, XmlRpcFaultException)
                    OnAddToUserGalleryCompleted(New AddToUserGalleryCompletedEventArgs() With {.Error = Mapper.Map(Of XmlRpcFaultException, [Error])(xmlrpcEx),
                                                                                               .Result = False,
                                                                                               .GalleryId = userTuple.Item3,
                                                                                               .UserState = userTuple.Item4,
                                                                                               .SessionId = userTuple.Item1,
                                                                                               .MediaId = userTuple.Item2})
                Else
                    Throw
                End If
            End Try
        End Sub

        Public Event AddToUserGalleryCompleted(ByVal sender As Object, ByVal e As AddToUserGalleryCompletedEventArgs) Implements IPartnerService.AddToUserGalleryCompleted

        Protected Sub OnAddToUserGalleryCompleted(e As AddToUserGalleryCompletedEventArgs)
            RaiseEvent AddToUserGalleryCompleted(Me, e)
        End Sub
#End Region

#Region "RemoveFromUserGallery"
        ''' <summary>
        ''' This methods allows you to remove a content from your default lightbox or any of your existing galleries. 
        ''' </summary>
        ''' <param name="sessionId">The session id.</param>
        ''' <param name="mediaId">The media id.</param>
        ''' <param name="galleryId">The gallery id.</param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Function RemoveFromUserGallery(ByVal sessionId As String, ByVal mediaId As Integer, ByVal galleryId As String) As Boolean Implements IPartnerService.RemoveFromUserGallery
            Dim retVal As Boolean = False
            Try
                UserProxy.CookieContainer.Add(New Cookie("PHPSESSID", sessionId, "/", ".fotolia.com"))
                Dim response = Me.UserProxy.RemoveFromUserGallery(Me.Authentication, sessionId, mediaId, If(galleryId Is Nothing, String.Empty, galleryId))
                If response.ContainsKey("removefromusergallery") Then
                    Dim result = response.Item("removefromusergallery").ToString()
                    If String.Compare(result, "SUCCESS", True) = 0 Then
                        retVal = True
                    End If
                End If
            Catch ex As Exception
                If TypeOf ex Is XmlRpcIllFormedXmlException Then
                    Throw New FotoliaException("Invalid Session Token", ex) With {.Code = "21"}
                Else
                    ManageException(ex)
                End If
            End Try
            Return retVal
        End Function

        ''' <summary>
        ''' This methods allows you to remove a content from your default lightbox or any of your existing galleries async.
        ''' </summary>
        ''' <param name="sessionId">The session id.</param>
        ''' <param name="mediaId">The media id.</param>
        ''' <param name="galleryId">The gallery id.</param>
        ''' <param name="userState">The user state object.</param>
        ''' <remarks></remarks>
        Public Sub RemoveFromUserGalleryAsync(ByVal sessionId As String, ByVal mediaId As Integer, ByVal galleryId As String, ByVal userState As Object) Implements IPartnerService.RemoveFromUserGalleryAsync
            Try
                UserProxy.CookieContainer.Add(New Cookie("PHPSESSID", sessionId, "/", ".fotolia.com"))
                UserProxy.BeginRemoveFromUserGallery(Me.Authentication, sessionId, mediaId, If(galleryId Is Nothing, String.Empty, galleryId),
                                                    AddressOf RemoveFromUserGalleryCallBack,
                                                    New Tuple(Of String, Integer, String, Object)(sessionId, mediaId, galleryId, userState))
            Catch ex As Exception
                If TypeOf ex Is XmlRpcFaultException Then
                    Dim xmlrpcEx = CType(ex, XmlRpcFaultException)
                    OnRemoveFromUserGalleryCompleted(New RemoveFromUserGalleryCompletedEventArgs() With {.Error = Mapper.Map(Of XmlRpcFaultException, [Error])(xmlrpcEx),
                                                                                                       .Result = False,
                                                                                                       .UserState = userState,
                                                                                                       .GalleryId = galleryId,
                                                                                                       .SessionId = sessionId,
                                                                                                       .MediaId = mediaId})
                Else
                    Throw
                End If
            End Try
        End Sub

        Private Sub RemoveFromUserGalleryCallBack(asr As IAsyncResult)
            Dim clientResult = CType(asr, XmlRpcAsyncResult)
            Dim proxy = CType(clientResult.ClientProtocol, IUser)
            Dim userTuple = CType(clientResult.AsyncState, Tuple(Of String, Integer, String, Object))
            Try
                Dim retval = False
                Dim asyncResult = proxy.EndAddToUserGallery(asr)
                If asyncResult.ContainsKey("removefromusergallery") Then
                    Dim result = asyncResult.Item("removefromusergallery").ToString()
                    If String.Compare(result, "SUCCESS", True) = 0 Then
                        retval = True
                    End If
                End If
                OnRemoveFromUserGalleryCompleted(New RemoveFromUserGalleryCompletedEventArgs() With {.Error = Nothing,
                                                                                           .Result = retval,
                                                                                           .UserState = userTuple.Item4,
                                                                                           .SessionId = userTuple.Item1,
                                                                                           .GalleryId = userTuple.Item3,
                                                                                           .MediaId = userTuple.Item2})
            Catch ex As Exception
                If TypeOf ex Is XmlRpcFaultException Then
                    Dim xmlrpcEx = CType(ex, XmlRpcFaultException)
                    OnRemoveFromUserGalleryCompleted(New RemoveFromUserGalleryCompletedEventArgs() With {.Error = Mapper.Map(Of XmlRpcFaultException, [Error])(xmlrpcEx),
                                                                                               .Result = False,
                                                                                               .GalleryId = userTuple.Item3,
                                                                                               .UserState = userTuple.Item4,
                                                                                               .SessionId = userTuple.Item1,
                                                                                               .MediaId = userTuple.Item2})
                Else
                    Throw
                End If
            End Try
        End Sub

        ''' <summary>
        ''' Occurs when [remove from user gallery completed].
        ''' </summary>
        ''' <remarks></remarks>
        Public Event RemoveFromUserGalleryCompleted(ByVal sender As Object, ByVal e As RemoveFromUserGalleryCompletedEventArgs) Implements IPartnerService.RemoveFromUserGalleryCompleted
        
        Protected Sub OnRemoveFromUserGalleryCompleted(e As RemoveFromUserGalleryCompletedEventArgs)
            RaiseEvent RemoveFromUserGalleryCompleted(Me, e)
        End Sub
#End Region

#Region "GetUserAdvancedStats"

        ''' <summary>
        ''' This methods allows you to get sales/views/income statistics from your account.
        ''' </summary>
        ''' <param name="sessionId">The user session id.</param>
        ''' <param name="type">Type of data to retrieve.</param>
        ''' <param name="range">Group by clause.</param>
        ''' <param name="period">Valid values for simple date statistics.</param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Function GetUserAdvancedStats(ByVal sessionId As String,
                                             ByVal type As UserStatsType,
                                             ByVal range As UserStatsTimeRange,
                                             ByVal period As UserStatsDatePeriod) As UserAdvancedStats Implements IPartnerService.GetUserAdvancedStats
            Dim retVal As UserAdvancedStats = Nothing
            Try
                retVal = GetResultFromCache(Of UserAdvancedStats)("GetUserAdvancedStats", Me.Authentication,
                                                            sessionId, type, range, period, Nothing, Nothing)

                If retVal Is Nothing Then
                    Dim result As XmlRpcStruct
                    UserProxy.CookieContainer.Add(New Cookie("PHPSESSID", sessionId, "/", ".fotolia.com"))

                    result = UserProxy.GetUserAdvancedStats(Me.Authentication, sessionId,
                                                          UserStatsTypes.GetTypeString(type),UserStatsTimeRanges.GetString(range),
                                                          UserStatsDatePeriods.GetString(period))

                    retVal = Mapper.Map(Of Tuple(Of XmlRpcStruct, Entities.UserStatsType, Entities.UserStatsTimeRange), Entities.UserAdvancedStats)(New Tuple(Of XmlRpcStruct, Entities.UserStatsType, Entities.UserStatsTimeRange)(result, type, range))
                    SetResultInCache(Of UserAdvancedStats)("GetUserAdvancedStats", retVal, Me.Authentication,
                                                            sessionId, type, range, period, Nothing, Nothing)
                End If
            Catch ex As Exception
                If TypeOf ex Is XmlRpcIllFormedXmlException Then
                    Throw New FotoliaException("Invalid Session Token", ex) With {.Code = "21"}
                Else
                    ManageException(ex)
                End If
            End Try
            Return retVal
        End Function

        ''' <summary>
        ''' This methods allows you to get sales/views/income statistics from your account. 
        ''' </summary>
        ''' <param name="sessionId">The user session id.</param>
        ''' <param name="type">Type of data to retrieve.</param>
        ''' <param name="range">Group by clause.</param>
        ''' <param name="startDate">The start date.</param>
        ''' <param name="endDate">The end date.</param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Function GetUserAdvancedStats(ByVal sessionId As String, ByVal type As UserStatsType, ByVal range As UserStatsTimeRange, ByVal startDate As Date, ByVal endDate As Date) As UserAdvancedStats Implements IPartnerService.GetUserAdvancedStats
            Dim retVal As UserAdvancedStats = Nothing
            Try
                retVal = GetResultFromCache(Of UserAdvancedStats)("GetUserAdvancedStats", Me.Authentication,
                                                            sessionId, type, range, Nothing, startDate, endDate)

                If retVal Is Nothing Then
                    Dim result As XmlRpcStruct
                    UserProxy.CookieContainer.Add(New Cookie("PHPSESSID", sessionId, "/", ".fotolia.com"))
                    Dim strDateStart = startDate.ToString("yyyy-MM-dd")
                    Dim strDateEnd = endDate.ToString("yyyy-MM-dd")
                    result = UserProxy.GetUserAdvancedStats2(Me.Authentication, sessionId,
                                                          UserStatsTypes.GetTypeString(type),UserStatsTimeRanges.GetString(range),
                                                          String.Empty,strDateStart,strDateEnd)
                    retVal = Mapper.Map(Of Tuple(Of XmlRpcStruct, Entities.UserStatsType, Entities.UserStatsTimeRange), Entities.UserAdvancedStats)(New Tuple(Of XmlRpcStruct, Entities.UserStatsType, Entities.UserStatsTimeRange)(result, type, range))
                    SetResultInCache(Of UserAdvancedStats)("GetUserAdvancedStats", retVal, Me.Authentication,
                                                            sessionId, type, range, Nothing, startDate, endDate)
                End If
            Catch ex As Exception
                If TypeOf ex Is XmlRpcIllFormedXmlException Then
                    Throw New FotoliaException("Invalid Session Token", ex) With {.Code = "21"}
                Else
                    ManageException(ex)
                End If
            End Try
            Return retVal
        End Function

        ''' <summary>
        ''' This methods allows you to get sales/views/income statistics from your account (in async mode). 
        ''' </summary>
        ''' <param name="sessionId">The user session id.</param>
        ''' <param name="type">Type of data to retrieve.</param>
        ''' <param name="range">Group by clause.</param>
        ''' <param name="period">Valid values for simple date statistics.</param>
        ''' <param name="userState">The user state object.</param>
        ''' <remarks></remarks>
        Public Sub GetUserAdvancedStatsAsync(ByVal sessionId As String, ByVal type As UserStatsType, ByVal range As UserStatsTimeRange, ByVal period As UserStatsDatePeriod, ByVal userState As Object) Implements IPartnerService.GetUserAdvancedStatsAsync
            Try
                Dim retVal = GetResultFromCache(Of UserAdvancedStats)("GetUserAdvancedStats", Me.Authentication,
                                                            sessionId, type, range, period, Nothing, Nothing)

                If retVal Is Nothing Then
                    UserProxy.CookieContainer.Add(New Cookie("PHPSESSID", sessionId, "/", ".fotolia.com"))
                    UserProxy.BeginGetUserAdvancedStats(Me.Authentication, sessionId,
                                                        UserStatsTypes.GetTypeString(type),
                                                        UserStatsTimeRanges.GetString(range),
                                                        UserStatsDatePeriods.GetString(period),
                                                        AddressOf GetUserAdvancedStatsCallBack,
                                                        New Tuple(Of String, UserStatsType, UserStatsTimeRange, UserStatsDatePeriod?, DateTime?, DateTime?, Object)(sessionId, type, range, period, Nothing, Nothing, userState))
                Else
                    OnGetUserAdvancedStatsCompleted(New GetUserAdvancedStatsCompletedEventArgs() With {.Error = Nothing, .Result = True, .UserState = userState,
                                                                                                               .SessionId = sessionId, .EndDate = Nothing, .Period = period,
                                                                                                                .Range = range, .StartDate = Nothing, .Type = type,
                                                                                                                .UserStats = retVal})
                End If
            Catch ex As Exception
                If TypeOf ex Is XmlRpcFaultException Then
                    Dim xmlrpcEx = CType(ex, XmlRpcFaultException)
                    OnGetUserAdvancedStatsCompleted(New GetUserAdvancedStatsCompletedEventArgs() With {.Error = Mapper.Map(Of XmlRpcFaultException, [Error])(xmlrpcEx),
                                                                                                                .Result = False, .UserState = userState,
                                                                                                                .SessionId = sessionId, .EndDate = Nothing, .Period = period,
                                                                                                                .Range = range, .StartDate = Nothing, .Type = type,
                                                                                                                .UserStats = Nothing})
                Else
                    Throw
                End If
            End Try
        End Sub

        ''' <summary>
        ''' This methods allows you to get sales/views/income statistics from your account. 
        ''' </summary>
        ''' <param name="sessionId">The user session id.</param>
        ''' <param name="type">Type of data to retrieve.</param>
        ''' <param name="range">Group by clause.</param>
        ''' <param name="startDate">The start date.</param>
        ''' <param name="endDate">The end date.</param>
        ''' <param name="userState">The user state object.</param>
        ''' <remarks></remarks>
        Public Sub GetUserAdvancedStatsAsync(ByVal sessionId As String, ByVal type As UserStatsType, ByVal range As UserStatsTimeRange, ByVal startDate As Date, ByVal endDate As Date, ByVal userState As Object) Implements IPartnerService.GetUserAdvancedStatsAsync
            Try
                Dim retVal = GetResultFromCache(Of UserAdvancedStats)("GetUserAdvancedStats", Me.Authentication,
                                                            sessionId, type, range, Nothing, startDate, endDate)

                If retVal Is Nothing Then
                    Dim strDateStart = startDate.ToString("yyyy-MM-dd")
                    Dim strDateEnd = endDate.ToString("yyyy-MM-dd")
                    UserProxy.CookieContainer.Add(New Cookie("PHPSESSID", sessionId, "/", ".fotolia.com"))
                    UserProxy.BeginGetUserAdvancedStats2(Me.Authentication, sessionId,
                                                        UserStatsTypes.GetTypeString(type),
                                                        UserStatsTimeRanges.GetString(range),
                                                        String.Empty,
                                                        strDateStart, strDateEnd,
                                                        AddressOf GetUserAdvancedStatsCallBack,
                                                        New Tuple(Of String, UserStatsType, UserStatsTimeRange, UserStatsDatePeriod?, DateTime?, DateTime?, Object)(sessionId, type, range, Nothing, startDate, endDate, userState))
                Else
                    OnGetUserAdvancedStatsCompleted(New GetUserAdvancedStatsCompletedEventArgs() With {.Error = Nothing, .Result = True, .UserState = userState,
                                                                                                               .SessionId = sessionId, .EndDate = endDate, .Period = Nothing,
                                                                                                                .Range = range, .StartDate = startDate, .Type = type,
                                                                                                                .UserStats = retVal})
                End If
            Catch ex As Exception
                If TypeOf ex Is XmlRpcFaultException Then
                    Dim xmlrpcEx = CType(ex, XmlRpcFaultException)
                    OnGetUserAdvancedStatsCompleted(New GetUserAdvancedStatsCompletedEventArgs() With {.Error = Mapper.Map(Of XmlRpcFaultException, [Error])(xmlrpcEx),
                                                                                                                .Result = False, .UserState = userState,
                                                                                                                .SessionId = sessionId, .EndDate = endDate, .Period = Nothing,
                                                                                                                .Range = range, .StartDate = startDate, .Type = type,
                                                                                                                .UserStats = Nothing})
                Else
                    Throw
                End If
            End Try
        End Sub

        Private Sub GetUserAdvancedStatsCallBack(asr As IAsyncResult)
            Dim clientResult = CType(asr, XmlRpcAsyncResult)
            Dim proxy = CType(clientResult.ClientProtocol, IUser)
            Dim userTuple = CType(clientResult.AsyncState, Tuple(Of String, UserStatsType, UserStatsTimeRange, UserStatsDatePeriod?, DateTime?, DateTime?, Object))
            Try
                Dim asyncResult = proxy.EndGetUserAdvancedStats(asr)
                Dim data = Mapper.Map(Of Tuple(Of XmlRpcStruct, Entities.UserStatsType, Entities.UserStatsTimeRange), Entities.UserAdvancedStats)(New Tuple(Of XmlRpcStruct, Entities.UserStatsType, Entities.UserStatsTimeRange)(asyncResult, userTuple.Item2, userTuple.Item3))
                SetResultInCache(Of UserAdvancedStats)("GetUserAdvancedStats", data, Me.Authentication,
                                                        userTuple.Item1, userTuple.Item2, userTuple.Item3, userTuple.Item4, userTuple.Item5, userTuple.Item6)

                OnGetUserAdvancedStatsCompleted(New GetUserAdvancedStatsCompletedEventArgs() With {.Error = Nothing,
                                                                                                            .Result = True, .UserState = userTuple.Item7,
                                                                                                            .SessionId = userTuple.Item1, .EndDate = userTuple.Item5,
                                                                                                            .Period = userTuple.Item4, .Range = userTuple.Item3,
                                                                                                            .StartDate = userTuple.Item5, .Type = userTuple.Item2,
                                                                                                            .UserStats = data})
            Catch ex As Exception
                If TypeOf ex Is XmlRpcFaultException Then
                    Dim xmlrpcEx = CType(ex, XmlRpcFaultException)
                    OnGetUserAdvancedStatsCompleted(New GetUserAdvancedStatsCompletedEventArgs() With {.Error = Mapper.Map(Of XmlRpcFaultException, [Error])(xmlrpcEx),
                                                                                                                .Result = False, .UserState = userTuple.Item7,
                                                                                                                .SessionId = userTuple.Item1, .EndDate = userTuple.Item5,
                                                                                                                .Period = userTuple.Item4, .Range = userTuple.Item3,
                                                                                                                .StartDate = userTuple.Item5, .Type = userTuple.Item2,
                                                                                                                .UserStats = Nothing})
                ElseIf TypeOf ex Is XmlRpcIllFormedXmlException Then
                    OnGetUserAdvancedStatsCompleted(New GetUserAdvancedStatsCompletedEventArgs() With {.Error = New FTTK.Error() With {.Code = "21",
                                                                                                                        .Message = "Invalid Session Token"},
                                                                                                                .Result = False, .UserState = userTuple.Item7,
                                                                                                                .SessionId = userTuple.Item1, .EndDate = userTuple.Item5,
                                                                                                                .Period = userTuple.Item4, .Range = userTuple.Item3,
                                                                                                                .StartDate = userTuple.Item5, .Type = userTuple.Item2,
                                                                                                                .UserStats = Nothing})
                Else
                    Throw
                End If
            End Try
        End Sub

        ''' <summary>
        ''' Occurs when [get user advanced stats completed].
        ''' </summary>
        ''' <remarks></remarks>
        Public Event GetUserAdvancedStatsCompleted(ByVal sender As Object, ByVal e As GetUserAdvancedStatsCompletedEventArgs) Implements IPartnerService.GetUserAdvancedStatsCompleted

        Protected Sub OnGetUserAdvancedStatsCompleted(e As GetUserAdvancedStatsCompletedEventArgs)
            RaiseEvent GetUserAdvancedStatsCompleted(Me, e)
        End Sub
#End Region

#Region "MoveUpMediaInUserGallery"
        ''' <summary>
        ''' Move a media up in an user gallery.
        ''' </summary>
        ''' <param name="sessionId">The user session id.</param>
        ''' <param name="mediaId">Existing media ID.</param>
        ''' <param name="galleryId">User gallery ID ID. If empty the default user gallery will be used</param>
        ''' <returns></returns>
        ''' <remarks>This method requires authentication with a valid session token.</remarks>
        Public Function MoveUpMediaInUserGallery(ByVal sessionId As String, ByVal mediaId As Integer, ByVal galleryId As String) As Boolean Implements IPartnerService.MoveUpMediaInUserGallery
            Dim retVal As Boolean = False
            Try
                UserProxy.CookieContainer.Add(New Cookie("PHPSESSID", sessionId, "/", ".fotolia.com"))
                Me.UserProxy.MoveUpMediaInUserGallery(Me.Authentication, sessionId, mediaId, If(galleryId Is Nothing, String.Empty, galleryId))
                retVal = True
            Catch ex As Exception
                If TypeOf ex Is XmlRpcIllFormedXmlException Then
                    Throw New FotoliaException("Invalid Session Token", ex) With {.Code = "21"}
                Else
                    ManageException(ex)
                End If
            End Try
            Return retVal
        End Function

        ''' <summary>
        ''' Moves up media in user gallery async.
        ''' </summary>
        ''' <param name="sessionId">The user session id.</param>
        ''' <param name="mediaId">Existing media ID.</param>
        ''' <param name="galleryId">User gallery ID ID. If empty the default user gallery will be used</param>
        ''' <param name="userState">The user state object.</param>
        ''' <remarks></remarks>
        Public Sub MoveUpMediaInUserGalleryAsync(ByVal sessionId As String, ByVal mediaId As Integer, ByVal galleryId As String, ByVal userState As Object) Implements IPartnerService.MoveUpMediaInUserGalleryAsync
            Try
                UserProxy.CookieContainer.Add(New Cookie("PHPSESSID", sessionId, "/", ".fotolia.com"))
                UserProxy.BeginMoveUpMediaInUserGallery(Me.Authentication, sessionId, mediaId, If(galleryId Is Nothing, String.Empty, galleryId),
                                                    AddressOf MoveUpMediaInUserGalleryCallBack,
                                                    New Tuple(Of String, Integer, String, Object)(sessionId, mediaId, galleryId, userState))
            Catch ex As Exception
                If TypeOf ex Is XmlRpcFaultException Then
                    Dim xmlrpcEx = CType(ex, XmlRpcFaultException)
                    OnMoveUpMediaInUserGalleryCompleted(New MoveUpMediaInUserGalleryCompletedEventArgs() With {.Error = Mapper.Map(Of XmlRpcFaultException, [Error])(xmlrpcEx),
                                                                                                       .Result = False,
                                                                                                       .UserState = userState,
                                                                                                       .GalleryId = galleryId,
                                                                                                       .SessionId = sessionId,
                                                                                                       .MediaId = mediaId})
                Else
                    Throw
                End If
            End Try
        End Sub

        Private Sub MoveUpMediaInUserGalleryCallBack(asr As IAsyncResult)
            Dim clientResult = CType(asr, XmlRpcAsyncResult)
            Dim proxy = CType(clientResult.ClientProtocol, IUser)
            Dim userTuple = CType(clientResult.AsyncState, Tuple(Of String, Integer, String, Object))
            Try
                proxy.EndMoveUpMediaInUserGallery(asr)
                OnMoveUpMediaInUserGalleryCompleted(New MoveUpMediaInUserGalleryCompletedEventArgs() With {.Error = Nothing,
                                                                                                           .Result = True,
                                                                                                           .UserState = userTuple.Item4,
                                                                                                           .SessionId = userTuple.Item1,
                                                                                                           .GalleryId = userTuple.Item3,
                                                                                                           .MediaId = userTuple.Item2})
            Catch ex As Exception
                If TypeOf ex Is XmlRpcFaultException Then
                    Dim xmlrpcEx = CType(ex, XmlRpcFaultException)
                    OnMoveUpMediaInUserGalleryCompleted(New MoveUpMediaInUserGalleryCompletedEventArgs() With {.Error = Mapper.Map(Of XmlRpcFaultException, [Error])(xmlrpcEx),
                                                                                                               .Result = False,
                                                                                                               .GalleryId = userTuple.Item3,
                                                                                                               .UserState = userTuple.Item4,
                                                                                                               .SessionId = userTuple.Item1,
                                                                                                               .MediaId = userTuple.Item2})
                Else
                    Throw
                End If
            End Try
        End Sub

        ''' <summary>
        ''' Occurs when [move up media in user gallery completed].
        ''' </summary>
        ''' <remarks></remarks>
        Public Event MoveUpMediaInUserGalleryCompleted(ByVal sender As Object, ByVal e As MoveUpMediaInUserGalleryCompletedEventArgs) Implements IPartnerService.MoveUpMediaInUserGalleryCompleted

        Protected Sub OnMoveUpMediaInUserGalleryCompleted(e As MoveUpMediaInUserGalleryCompletedEventArgs)
            RaiseEvent MoveUpMediaInUserGalleryCompleted(Me, e)
        End Sub
#End Region

#Region "MoveDownMediaInUserGallery"
        ''' <summary>
        ''' Move a media down in an user gallery.
        ''' </summary>
        ''' <param name="sessionId">The user session id.</param>
        ''' <param name="mediaId">Existing media ID.</param>
        ''' <param name="galleryId">User gallery ID ID. If empty the default user gallery will be used</param>
        ''' <returns></returns>
        ''' <remarks>This method requires authentication with a valid session token.</remarks>
        Public Function MoveDownMediaInUserGallery(ByVal sessionId As String, ByVal mediaId As Integer, ByVal galleryId As String) As Boolean Implements IPartnerService.MoveDownMediaInUserGallery
            Dim retVal As Boolean = False
            Try
                UserProxy.CookieContainer.Add(New Cookie("PHPSESSID", sessionId, "/", ".fotolia.com"))
                Me.UserProxy.MoveDownMediaInUserGallery(Me.Authentication, sessionId, mediaId, If(galleryId Is Nothing, String.Empty, galleryId))
                retVal = True
            Catch ex As Exception
                If TypeOf ex Is XmlRpcIllFormedXmlException Then
                    Throw New FotoliaException("Invalid Session Token", ex) With {.Code = "21"}
                Else
                    ManageException(ex)
                End If
            End Try
            Return retVal
        End Function

        ''' <summary>
        ''' Moves down media in user gallery async.
        ''' </summary>
        ''' <param name="sessionId">The user session id.</param>
        ''' <param name="mediaId">Existing media ID.</param>
        ''' <param name="galleryId">User gallery ID ID. If empty the default user gallery will be used</param>
        ''' <param name="userState">The user state object.</param>
        ''' <remarks></remarks>
        Public Sub MoveDownMediaInUserGalleryAsync(ByVal sessionId As String, ByVal mediaId As Integer, ByVal galleryId As String, ByVal userState As Object) Implements IPartnerService.MoveDownMediaInUserGalleryAsync
            Try
                UserProxy.CookieContainer.Add(New Cookie("PHPSESSID", sessionId, "/", ".fotolia.com"))
                UserProxy.BeginMoveDownMediaInUserGallery(Me.Authentication, sessionId, mediaId, If(galleryId Is Nothing, String.Empty, galleryId),
                                                    AddressOf MoveDownMediaInUserGalleryCallBack,
                                                    New Tuple(Of String, Integer, String, Object)(sessionId, mediaId, galleryId, userState))
            Catch ex As Exception
                If TypeOf ex Is XmlRpcFaultException Then
                    Dim xmlrpcEx = CType(ex, XmlRpcFaultException)
                    OnMoveDownMediaInUserGalleryCompleted(New MoveDownMediaInUserGalleryCompletedEventArgs() With {.Error = Mapper.Map(Of XmlRpcFaultException, [Error])(xmlrpcEx),
                                                                                                       .Result = False,
                                                                                                       .UserState = userState,
                                                                                                       .GalleryId = galleryId,
                                                                                                       .SessionId = sessionId,
                                                                                                       .MediaId = mediaId})
                Else
                    Throw
                End If
            End Try
        End Sub

        Private Sub MoveDownMediaInUserGalleryCallBack(asr As IAsyncResult)
            Dim clientResult = CType(asr, XmlRpcAsyncResult)
            Dim proxy = CType(clientResult.ClientProtocol, IUser)
            Dim userTuple = CType(clientResult.AsyncState, Tuple(Of String, Integer, String, Object))
            Try
                proxy.EndMoveDownMediaInUserGallery(asr)
                OnMoveDownMediaInUserGalleryCompleted(New MoveDownMediaInUserGalleryCompletedEventArgs() With {.Error = Nothing,
                                                                                                           .Result = True,
                                                                                                           .UserState = userTuple.Item4,
                                                                                                           .SessionId = userTuple.Item1,
                                                                                                           .GalleryId = userTuple.Item3,
                                                                                                           .MediaId = userTuple.Item2})
            Catch ex As Exception
                If TypeOf ex Is XmlRpcFaultException Then
                    Dim xmlrpcEx = CType(ex, XmlRpcFaultException)
                    OnMoveDownMediaInUserGalleryCompleted(New MoveDownMediaInUserGalleryCompletedEventArgs() With {.Error = Mapper.Map(Of XmlRpcFaultException, [Error])(xmlrpcEx),
                                                                                                               .Result = False,
                                                                                                               .GalleryId = userTuple.Item3,
                                                                                                               .UserState = userTuple.Item4,
                                                                                                               .SessionId = userTuple.Item1,
                                                                                                               .MediaId = userTuple.Item2})
                Else
                    Throw
                End If
            End Try
        End Sub

        ''' <summary>
        ''' Occurs when [move down media in user gallery completed].
        ''' </summary>
        ''' <remarks></remarks>
        Public Event MoveDownMediaInUserGalleryCompleted(ByVal sender As Object, ByVal e As MoveDownMediaInUserGalleryCompletedEventArgs) Implements IPartnerService.MoveDownMediaInUserGalleryCompleted

        Protected Sub OnMoveDownMediaInUserGalleryCompleted(e As MoveDownMediaInUserGalleryCompletedEventArgs)
            RaiseEvent MoveDownMediaInUserGalleryCompleted(Me, e)
        End Sub
#End Region

#Region "MoveMediaToTopInUserGallery"
        ''' <summary>
        ''' Move a media down in an user gallery.
        ''' </summary>
        ''' <param name="sessionId">The user session id.</param>
        ''' <param name="mediaId">Existing media ID.</param>
        ''' <param name="galleryId">User gallery ID ID. If empty the default user gallery will be used</param>
        ''' <returns></returns>
        ''' <remarks>This method requires authentication with a valid session token.</remarks>
        Public Function MoveMediaToTopInUserGallery(ByVal sessionId As String, ByVal mediaId As Integer, ByVal galleryId As String) As Boolean Implements IPartnerService.MoveMediaToTopInUserGallery
            Dim retVal As Boolean = False
            Try
                UserProxy.CookieContainer.Add(New Cookie("PHPSESSID", sessionId, "/", ".fotolia.com"))
                Me.UserProxy.MoveMediaToTopInUserGallery(Me.Authentication, sessionId, mediaId, If(galleryId Is Nothing, String.Empty, galleryId))
                retVal = True
            Catch ex As Exception
                If TypeOf ex Is XmlRpcIllFormedXmlException Then
                    Throw New FotoliaException("Invalid Session Token", ex) With {.Code = "21"}
                Else
                    ManageException(ex)
                End If
            End Try
            Return retVal
        End Function

        ''' <summary>
        ''' Moves down media in user gallery async.
        ''' </summary>
        ''' <param name="sessionId">The user session id.</param>
        ''' <param name="mediaId">Existing media ID.</param>
        ''' <param name="galleryId">User gallery ID ID. If empty the default user gallery will be used</param>
        ''' <param name="userState">The user state object.</param>
        ''' <remarks></remarks>
        Public Sub MoveMediaToTopInUserGalleryAsync(ByVal sessionId As String, ByVal mediaId As Integer, ByVal galleryId As String, ByVal userState As Object) Implements IPartnerService.MoveMediaToTopInUserGalleryAsync
            Try
                UserProxy.CookieContainer.Add(New Cookie("PHPSESSID", sessionId, "/", ".fotolia.com"))
                UserProxy.BeginMoveMediaToTopInUserGallery(Me.Authentication, sessionId, mediaId, If(galleryId Is Nothing, String.Empty, galleryId),
                                                    AddressOf MoveMediaToTopInUserGalleryCallBack,
                                                    New Tuple(Of String, Integer, String, Object)(sessionId, mediaId, galleryId, userState))
            Catch ex As Exception
                If TypeOf ex Is XmlRpcFaultException Then
                    Dim xmlrpcEx = CType(ex, XmlRpcFaultException)
                    OnMoveMediaToTopInUserGalleryCompleted(New MoveMediaToTopInUserGalleryCompletedEventArgs() With {.Error = Mapper.Map(Of XmlRpcFaultException, [Error])(xmlrpcEx),
                                                                                                       .Result = False,
                                                                                                       .UserState = userState,
                                                                                                       .GalleryId = galleryId,
                                                                                                       .SessionId = sessionId,
                                                                                                       .MediaId = mediaId})
                Else
                    Throw
                End If
            End Try
        End Sub

        Private Sub MoveMediaToTopInUserGalleryCallBack(asr As IAsyncResult)
            Dim clientResult = CType(asr, XmlRpcAsyncResult)
            Dim proxy = CType(clientResult.ClientProtocol, IUser)
            Dim userTuple = CType(clientResult.AsyncState, Tuple(Of String, Integer, String, Object))
            Try
                proxy.EndMoveMediaToTopInUserGallery(asr)
                OnMoveMediaToTopInUserGalleryCompleted(New MoveMediaToTopInUserGalleryCompletedEventArgs() With {.Error = Nothing,
                                                                                                           .Result = True,
                                                                                                           .UserState = userTuple.Item4,
                                                                                                           .SessionId = userTuple.Item1,
                                                                                                           .GalleryId = userTuple.Item3,
                                                                                                           .MediaId = userTuple.Item2})
            Catch ex As Exception
                If TypeOf ex Is XmlRpcFaultException Then
                    Dim xmlrpcEx = CType(ex, XmlRpcFaultException)
                    OnMoveMediaToTopInUserGalleryCompleted(New MoveMediaToTopInUserGalleryCompletedEventArgs() With {.Error = Mapper.Map(Of XmlRpcFaultException, [Error])(xmlrpcEx),
                                                                                                               .Result = False,
                                                                                                               .GalleryId = userTuple.Item3,
                                                                                                               .UserState = userTuple.Item4,
                                                                                                               .SessionId = userTuple.Item1,
                                                                                                               .MediaId = userTuple.Item2})
                Else
                    Throw
                End If
            End Try
        End Sub

        ''' <summary>
        ''' Occurs when [move down media in user gallery completed].
        ''' </summary>
        ''' <remarks></remarks>
        Public Event MoveMediaToTopInUserGalleryCompleted(ByVal sender As Object, ByVal e As MoveMediaToTopInUserGalleryCompletedEventArgs) Implements IPartnerService.MoveMediaToTopInUserGalleryCompleted

        Protected Sub OnMoveMediaToTopInUserGalleryCompleted(e As MoveMediaToTopInUserGalleryCompletedEventArgs)
            RaiseEvent MoveMediaToTopInUserGalleryCompleted(Me, e)
        End Sub
#End Region
    End Class
End Namespace